In [1]:
# # # Rules to Define Identifiers in Python :-
In [31]:
# 1. Allowed Characters in Python :-
# a to z
# A to Z
# 0 to 9
# _(Underscore)
In [3]:
cash = 10
In [4]:
cas$h = 10
Cell In[4], line 1 cas$h = 10 ^ SyntaxError: invalid syntax
In [5]:
cash_amount = 10
In [6]:
# 2. Identifier should not start with digit
In [7]:
total123 = 100
In [8]:
123total = 100
Cell In[8], line 1 123total = 100 ^ SyntaxError: invalid decimal literal
In [9]:
# 3. Python identifiers are case sensitive
In [10]:
total = 10
In [11]:
Total = 20
In [12]:
TOTAL = 30
In [26]:
# 4. no length limit, but not recommended to take lengthy identifiers
In [27]:
# 5. we cannot use keyword or reserved characters as identifiers
In [28]:
x = 10
In [29]:
if = 20
Cell In[29], line 1 if = 20 ^ SyntaxError: invalid syntax
In [33]:
# # Note :-
# x --> normal variable or public variable
# _x --> protected variable
# __x --> private variable
# __x__ --> magical word
# ex. __name__, __add__, __doc__, __sub__
In [37]:
__x = 10
type(__x)
Out[37]:
int
In [ ]:
# # # Reserved Words :-
In [38]:
# Some words are reserved to represent some functionality or meaning
# We have only 35 reserved words in Python
In [39]:
# True, False, None ===> Values.Reserved Literals
# and, or, not, is
# if, elif, else
# while, for, break, continue, return, in, yield
# try, except, finally, raise, assert
# import, from, as, class, def, pass, global, nonlocal, lambda, del, with
In [40]:
# # In Python 3.5 version new keyword introduced in Python :-
# async, await
# For asynchronous processing
In [6]:
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
In [9]:
# 1. All reserved words contain only alphabet symbols
# 2. The only reserved words contain upper case aplhabet symbol
# True, False, None
# 3. Switch statement is not applicable in Python
# 4. do-while loop is not there
# 5. no keywords like int, float, boolean etc
In [ ]:
In [ ]:
# # # Data Types :-
In [1]:
# Data Type Represent the type of data represented by a variable
In [3]:
x = 10
x = True
x = 10.5
# Dynamically Typed: Python, JavaScript, ShellScripting etc
In [4]:
# int x = 10;
# boolean b = true;
# Statically Typed: Java, C, C++
In [5]:
# # Types of Data Types :-
# int
# float
# complex
# bool
# str
# list
# tuple
# set
# frozenset
# dict
# bytes
# bytearray
# range
# None
In [6]:
# # The 3 most commonly used in python's in built functions :-
# In Linux everything is treated as a File
# In Python everything is treated as Object
# x = 10
# 1. print(x)
# 2. type(x)
# 3. id(x) -->Address of Object
In [7]:
x = 10
In [8]:
print(x)
10
In [12]:
type(x)
Out[12]:
int
In [13]:
id(x)
Out[13]:
140731415577672
In [14]:
x = [10, 20, 30, 40, 50, 60, 70, 80]
print(x)
print(type(x))
print(id(x))
[10, 20, 30, 40, 50, 60, 70, 80] <class 'list'> 2362951932544
In [15]:
# # # int Data Type :-
In [19]:
# To represent integral values
x = 10
print(type(x))
<class 'int'>
In [20]:
# # In Java we have :-
# byte: -128 to +127
# short: -32768 to 32767
# int: -2147483648 to 2147483647
# long: -2^63 to 2^63-1
In [21]:
x = 12134154687464634163746743216546874316574687431324865746431349874674321658746
In [22]:
# We have only 2 data types :-
# int
# long
In [23]:
# # Note :- In Python 2 we have int and long data type but in Python 3 we have only int data type
In [24]:
# # We can represent int values in multiple ways :-
# 1. Decimal Form(base-10)
# 2. Binary Form(base-2)
# 3. Octal Form(base-8)
# 4. Hexa Decimal Form(base-16)
In [28]:
# # 1. Decimal Form(base-10) :-
# The allowed digits are 0 to 9
# Example:
# x = 12345
In [32]:
# # 2. Binary Form(base-2) :-
# The allowed digits are 0 to 1
# The number should be prefixed with 0b or 0B
# Example:
# a = 0B1111
# a = 0b1111
In [34]:
a = 1111
b = 0b1111
print(a)
print(b)
print(type(a))
print(type(b))
1111 15 <class 'int'> <class 'int'>
In [35]:
# Convert Binary to Integer :-
# ( 1 1 1 1 ) = (?)
# 2^3 2^2 2^1 2^0
# 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0
# 1*8 + 1*4 + 1*2 + 1*1
# 8 + 4 + 2 + 1
# => 15
In [36]:
# # 3. Octal Form(base-8) :-
# The allowed digits are 0 to 7
# The number should be prefixed with 0o or 0O
# Example:
# a = 0O0123
# a = 0o0123
In [38]:
a = 0o0123
b = 0O0123
print(a)
print(b)
print(type(a))
print(type(b))
83 83 <class 'int'> <class 'int'>
In [39]:
# Convert Octal to Integer :-
# ( 0 1 2 3 ) = (?)
# 8^3 8^2 8^1 8^0
# 0*8^3 + 1*8^2 + 2*8^1 + 3*8^0
# 0*512 + 1*64 + 2*8 + 3*1
# 0 + 64 + 16 + 3
# => 83
In [41]:
a = 0o123
b = 0b11
print(a)
print(b)
print(a + b)
83 3 86
In [42]:
# # 4. Hexa Decimal Form(base-16) :-
# The allowed digits are:
# 0 to 9, A to F
# A-->10
# B-->11
# C-->12
# D-->13
# E-->14
# F-->15
# A - F or a - f
# The number should be prefixed with 0x or 0X
# Example:
# a = 0x0123Face
# a = 0X0123Face
In [43]:
a = 0x0123Face
b = 0X0123Face
print(a)
print(b)
print(type(a))
print(type(b))
19135182 19135182 <class 'int'> <class 'int'>
In [44]:
# Base-2 0 to 1
# Base-8 0 to 7
# Base-10 0 to 9
# Base-16 0 to 15
In [53]:
a = 0X012
print(a)
18
In [54]:
# Convert Hexa Decimal to Integer :-
# ( 0 1 2 ) = (?)
# 16^2 16^1 16^0
# 0*16^2 + 1*16^1 + 2*16*0
# 0*256 + 1*16 + 2*1
# 0 + 16 + 2
# => 18
In [55]:
# # Base Conversion Functions :-
# 1. bin()
# 2. oct()
# 3. hex()
In [ ]:
# bin(x)--> Provides Equivalent Binary Value
# x can be any value like ocatl or decimal or hexa decimal number
In [56]:
a = 10
print(a)
b = bin(a)
print(b)
10 0b1010
In [58]:
print(bin(10))
print(bin(0o10))
print(bin(0x10))
0b1010 0b1000 0b10000
In [59]:
print(oct(10))
0o12
In [60]:
print(hex(10))
0xa
In [ ]:
In [1]:
# # # Float Data Type :-
In [4]:
# Number with decimal point
f = 1.023
In [5]:
f = 0b1.1101
Cell In[5], line 1 f = 0b1.1101 ^ SyntaxError: invalid syntax
In [6]:
f = 0o1.1101
Cell In[6], line 1 f = 0o1.1101 ^ SyntaxError: invalid syntax
In [7]:
f = 0x1.1101
Cell In[7], line 1 f = 0x1.1101 ^ SyntaxError: invalid syntax
In [8]:
# Float values we should specify only in decimal format
In [11]:
# Exponential form or Scientific notation
f = 1.2e3
print(f)
1200.0
In [12]:
f = 1.2E3
print(f)
1200.0
In [14]:
# We can represent big values in less memory
a = 120000000000000000000000000000000000000
print(a)
b = 12e16
print(b)
120000000000000000000000000000000000000 1.2e+17
In [15]:
# Conditions for Float Data Type :-
# 1. with decimal point
# 2. only in decimal
# 3. exponential form
In [16]:
# # # Complex Data Type :-
In [33]:
# In C, C++, Java-->complex data type not available
# Format :-
# a+bj
# a is real number
# b is imaginary part
# j is fixed variable
# For a we can use any base
# For b we should use only decimal form
In [19]:
c = 10 + 20j
print(c)
(10+20j)
In [20]:
c = -10 -25j
print(c)
(-10-25j)
In [21]:
# For a, b we can use both int, float values
In [23]:
c = 10.5 + 20.6j
print(c)
(10.5+20.6j)
In [24]:
c = 0B1111 + 20j
print(c)
(15+20j)
In [25]:
c = 0B1111 + 0b0111j
Cell In[25], line 1 c = 0B1111 + 0b0111j ^ SyntaxError: invalid binary literal
In [27]:
a = 10 + 20j
b = 20 + 30j
print(a+b)
print(a-b)
print(a/b)
print(a*b)
(30+50j) (-10-10j) (0.6153846153846154+0.0769230769230769j) (-400+700j)
In [36]:
c = 10*20j # 10*(0+20j)
print(c)
200j
In [32]:
a = 10 + 20.5j
print(a.real)
print(a.imag)
10.0 20.5
In [34]:
a = True + 20.5j
print(a)
(1+20.5j)
In [37]:
# # # Boolean Data Type :-
In [39]:
# boolean values / logical values
# Example:
# True --> 1
# False --> 0
In [41]:
a = True
print(a)
b = False
print(b)
True False
In [42]:
# Comparison Operation:
age = 30
if age > 25:
print('AGE is greater than 25')
AGE is greater than 25
In [45]:
True + True
Out[45]:
2
In [46]:
True + False
Out[46]:
1
In [47]:
True * False
Out[47]:
0
In [48]:
True + Truej
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[48], line 1 ----> 1 True + Truej NameError: name 'Truej' is not defined
In [49]:
True + 20j
Out[49]:
(1+20j)
In [50]:
# # # Str Data Type :-
In [52]:
# str --> string
# Any sequence of character within either single quotes or double quotes
In [61]:
s = 'Pulkit'
print(s)
Pulkit
In [62]:
s = "Pulkit"
print(s)
Pulkit
In [63]:
s = Pulkit
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[63], line 1 ----> 1 s = Pulkit NameError: name 'Pulkit' is not defined
In [64]:
s = 'Pulkit"
Cell In[64], line 1 s = 'Pulkit" ^ SyntaxError: unterminated string literal (detected at line 1)
In [65]:
s = '''Pulkit
Chahal
Python
Practice'''
print(s)
Pulkit
Chahal
Python
Practice
In [66]:
# Multi line String Literals :-
# triple quotes
# triple single quotes
# triple double quotes
In [67]:
s = """Pulkit
Chahal
Python
Practice"""
print(s)
Pulkit
Chahal
Python
Practice
In [69]:
s = "Python classes by 'Durga Sir' are average"
print(s)
Python classes by 'Durga Sir' are average
In [70]:
s = 'Python classes by "Durga Sir" are average'
print(s)
Python classes by "Durga Sir" are average
In [71]:
s = 'Python 'classes' by "Durga Sir" are average'
Cell In[71], line 1 s = 'Python 'classes' by "Durga Sir" are average' ^ SyntaxError: invalid syntax
In [72]:
s = '''Python 'classes' by "Durga Sir" are average'''
print(s)
Python 'classes' by "Durga Sir" are average
In [77]:
s1 = '''Pulkit'''
s2 = 'Pulkit'
s3 = "Pulkit"
In [78]:
s1
Out[78]:
'Pulkit'
In [79]:
s2
Out[79]:
'Pulkit'
In [80]:
s3
Out[80]:
'Pulkit'
In [81]:
s = 'Python \'classes\' by "Durga Sir" are average'
print(s)
Python 'classes' by "Durga Sir" are average
In [82]:
s = "Python \'classes\' by \"Durga Sir\" are average"
print(s)
Python 'classes' by "Durga Sir" are average
In [84]:
# We use strings:-
# 1. To define multiline string literals
# 2. To use single quote or double quote as normal character
In [85]:
s = 'durga'
In [86]:
s[0]
Out[86]:
'd'
In [87]:
s[1]
Out[87]:
'u'
In [88]:
s[2]
Out[88]:
'r'
In [90]:
s[10]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[90], line 1 ----> 1 s[10] IndexError: string index out of range
In [91]:
# +ve index always from left to right
# -ve index always from right to left
In [92]:
s[-1]
Out[92]:
'a'
In [93]:
s[-2]
Out[93]:
'g'
In [94]:
s[-3]
Out[94]:
'r'
In [98]:
s[-6]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[98], line 1 ----> 1 s[-6] IndexError: string index out of range
In [99]:
s[len(s)-1]
Out[99]:
'a'
In [ ]:
In [4]:
# # # Slice Operator :-
In [81]:
# peice --> part
# [] to retreive part(slice) of the string
# s[begin:end] -> returns substring from index to end-1 index
In [12]:
s = 'abcdefghijklmnopqrstuvwxyz'
s[5:11] # begin to end-1
Out[12]:
'fghijk'
In [10]:
# If we are taking begin, then it will consider from begining of the string i.e default value is : 0
s[:8] # from 0 to 7
Out[10]:
'abcdefgh'
In [9]:
# If we are not specifying end index until end of string
s[3:] # from 3 to end of string
Out[9]:
'defghijklmnopqrstuvwxyz'
In [11]:
s[:] # from 0 to end of string
Out[11]:
'abcdefghijklmnopqrstuvwxyz'
In [14]:
# s and s[:]
In [15]:
s
Out[15]:
'abcdefghijklmnopqrstuvwxyz'
In [16]:
s[:]
Out[16]:
'abcdefghijklmnopqrstuvwxyz'
In [17]:
# Slice operaator won't raise any IndexError.
# If the index is out of range, then it will consider upto available characters only.
In [18]:
s[0:2689] # from 0 to last
Out[18]:
'abcdefghijklmnopqrstuvwxyz'
In [19]:
s[26] # IndexError: string index out of range
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[19], line 1 ----> 1 s[26] IndexError: string index out of range
In [20]:
s[3:5] # from begin index to end-1
# from 3 to 4
Out[20]:
'de'
In [1]:
s1 = 'aabcdefghijklmnopqrstuvwxyz '
In [2]:
s1[:24656874]
Out[2]:
'aabcdefghijklmnopqrstuvwxyz '
In [3]:
s1[154687:1564687463]
Out[3]:
''
In [21]:
s[2:7]
Out[21]:
'cdefg'
In [22]:
s[7:2]
Out[22]:
''
In [24]:
s[7:4] # from 7 to 3rd index in forward direction
Out[24]:
''
In [25]:
# s[begin:end:step]
In [30]:
# Print the given string with first character as uppercase
s = 'durga'
s[0].upper()+s[1:]
Out[30]:
'Durga'
In [37]:
# Print the given string with last character as uppercase
s = 'durga'
s[0:-1] + s[-1].upper()
# or
s[0:len(s)-1] + s[-1].upper()
Out[37]:
'durgA'
In [40]:
# First and last character capital
s = 'pulkitchahal'
s[0].upper() + s[1:len(s)-1] + s[-1].upper()
Out[40]:
'PulkitchahaL'
In [42]:
# # # Mathematical Operator for the String :-
In [44]:
s = 'pulkit' + 'chahal'
s
Out[44]:
'durgasoft'
In [54]:
s = ' ' + 'chahal'
s
Out[54]:
' chahal'
In [52]:
s = 'durga' + 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[52], line 1 ----> 1 s = 'durga' + 10 TypeError: can only concatenate str (not "int") to str
In [51]:
s = 10 + 'durga'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[51], line 1 ----> 1 s = 10 + 'durga' TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [55]:
s = '10' + 'durga'
s
Out[55]:
'10durga'
In [56]:
s = 'durga' + '10'
s
Out[56]:
'durga10'
In [57]:
# If we apply + operator for the strings both arguments should be str type only
In [60]:
# String Repition Operator(* -> Multiplication) ->
In [62]:
s = 'durga' * 5
s
Out[62]:
'durgadurgadurgadurgadurga'
In [65]:
s = 5 * 'durga'
s
Out[65]:
'durgadurgadurgadurgadurga'
In [63]:
s = 'durga' * 'soft'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[63], line 1 ----> 1 s = 'durga' * 'soft' TypeError: can't multiply sequence by non-int of type 'str'
In [66]:
# int + int
# str + str
# int * str
# str * int
# if we apply * for string one argument should be int
In [67]:
s = 2 * 'ab' * 3
s
Out[67]:
'abababababab'
In [69]:
# # # Fundamental data types of Python :-
# int
# float
# complex
# bool
# str
In [70]:
# # # Type Casting :-
In [71]:
# int()
# float()
# complex()
# bool()
# str()
In [72]:
# # 1. int() ->
In [80]:
# We can use this function to convert from other types to int
# int(x)
# We can convert from any type to int type except comlex type.
# If we want to convert str to int type, string should represent only integral value and should be specified only in decimal form(base-10)
In [3]:
int(10.5)
Out[3]:
10
In [74]:
int('10')
Out[74]:
10
In [77]:
int('10.5')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[77], line 1 ----> 1 int('10.5') ValueError: invalid literal for int() with base 10: '10.5'
In [75]:
int(True)
Out[75]:
1
In [76]:
int(10+20j)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[76], line 1 ----> 1 int(10+20j) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'complex'
In [78]:
int('0B1001')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[78], line 1 ----> 1 int('0B1001') ValueError: invalid literal for int() with base 10: '0B1001'
In [2]:
int('durga')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[2], line 1 ----> 1 int('durga') ValueError: invalid literal for int() with base 10: 'durga'
In [ ]:
# float --> int int(10.5)
# complex --> int int(10+20j) # Error
# bool --> int int(True)-->1
# str --> int int('123')
In [63]:
# # 2. float() :-
In [64]:
# convert from other types to float type
# int --> float float(10)
# complex --> float float(10+20j) # Error
# bool --> float float(True)
# str --> float float('10') float('10.5')
# cannot convert complex to float
# str should contains either integral value or floating point value, but compulsory we should use base-10 only
In [1]:
float(0B01010)
Out[1]:
10.0
In [65]:
float('0B01010')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[65], line 1 ----> 1 float('0B01010') ValueError: could not convert string to float: '0B01010'
In [66]:
float(10+20j)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[66], line 1 ----> 1 float(10+20j) TypeError: float() argument must be a string or a real number, not 'complex'
In [67]:
float(True)
Out[67]:
1.0
In [68]:
float('10')
Out[68]:
10.0
In [69]:
float('10.5')
Out[69]:
10.5
In [70]:
float(0X01011)
Out[70]:
4113.0
In [71]:
float('ten')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[71], line 1 ----> 1 float('ten') ValueError: could not convert string to float: 'ten'
In [ ]:
# # 3. complex() :-
In [ ]:
# from other types to complex type
# a+bj
# From any type complex is possible
# complex(x), complex(x,y)
In [ ]:
# complex(x):
# x will become real part
# imaginary part will become 0
# complex(x,y):
# x will become real part
# y will become imaginary part
In [ ]:
# The second argument can not be string.
# If the first argument is string, then we can not pass second argument.
In [72]:
complex(10)
Out[72]:
(10+0j)
In [73]:
complex(10.5)
Out[73]:
(10.5+0j)
In [74]:
complex(True)
Out[74]:
(1+0j)
In [75]:
complex('10')
Out[75]:
(10+0j)
In [76]:
complex('10.5')
Out[76]:
(10.5+0j)
In [37]:
complex('10.5j')
Out[37]:
10.5j
In [77]:
complex('ten')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[77], line 1 ----> 1 complex('ten') ValueError: complex() arg is a malformed string
In [2]:
complex(10,5)
Out[2]:
(10+5j)
In [78]:
complex(10.5,2.5)
Out[78]:
(10.5+2.5j)
In [79]:
complex(True,False)
Out[79]:
(1+0j)
In [38]:
complex('10','20')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[38], line 1 ----> 1 complex('10','20') TypeError: complex() can't take second arg if first is a string
In [39]:
complex(10,'20')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[39], line 1 ----> 1 complex(10,'20') TypeError: complex() second arg can't be a string
In [40]:
complex('10',20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[40], line 1 ----> 1 complex('10',20) TypeError: complex() can't take second arg if first is a string
In [5]:
complex(10,True)
Out[5]:
(10+1j)
In [6]:
complex(10.5,False)
Out[6]:
(10.5+0j)
In [7]:
complex(True, 10.5)
Out[7]:
(1+10.5j)
In [8]:
complex('10',True)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 1 ----> 1 complex('10',True) TypeError: complex() can't take second arg if first is a string
In [9]:
complex(0B0111, 0X10134)
Out[9]:
(7+65844j)
In [10]:
# # 4. bool() :-
In [11]:
# From other types to bool
# int --> bool zero means False and non-zero means True
# bool(0) ==> False
# bool(1) ==> True
# bool(2) ==> True
# float --> bool zero means False and non-zero means True
# bool(0.0) ==> False
# bool(0.0001) ==> True
# complex --> bool If both real and imaginary parts are zero then it is False otherwise it is True
# bool(0+0j) ==> False
# bool(0+0.1j) ==> True
# str --> bool If string is empty then False else True
# bool('True') ==> True
# bool('False') ==> True
# bool('Yes') ==> True
# bool('No') ==> True
# bool('') ==> False
In [12]:
bool(0)
Out[12]:
False
In [13]:
bool(1)
Out[13]:
True
In [14]:
bool(2)
Out[14]:
True
In [41]:
bool(-2)
Out[41]:
True
In [15]:
bool(0.0)
Out[15]:
False
In [16]:
bool(0.0001)
Out[16]:
True
In [17]:
bool(0+0j)
Out[17]:
False
In [18]:
bool(0+0.1j)
Out[18]:
True
In [19]:
bool('True')
Out[19]:
True
In [20]:
bool(' ')
Out[20]:
True
In [21]:
bool('')
Out[21]:
False
In [22]:
bool('False')
Out[22]:
True
In [23]:
# # 5. str() :-
In [24]:
# can convert any type to str
In [25]:
str(10)
Out[25]:
'10'
In [26]:
str(10.5)
Out[26]:
'10.5'
In [27]:
str(10+20j)
Out[27]:
'(10+20j)'
In [28]:
str(True)
Out[28]:
'True'
In [29]:
str(0B01111)
Out[29]:
'15'
In [30]:
# # # Fundamental Data Types Vs Immutability :-
In [31]:
# All Fundamental Data Types are immutable
# In Python everything is treated as object only
# Immutable ==> we cannot change
# Once we creates an object, we cannot change its content.
# If we are trying to change the content, with those cahnges a new object will be created.
In [42]:
x = 10
y = x
print(id(x))
print(id(y))
140731415577672 140731415577672
In [43]:
y = y+1
print(id(x))
print(id(y))
140731415577672 140731415577704
In [44]:
x = True
print(id(x))
y = False
print(id(y))
140731414104640 140731414104672
In [46]:
x = 10
print(id(x))
x = float(x)
print(id(x))
140731415577672 1348341995856
In [47]:
x = 10
print(id(x))
x = x+1
print(id(x))
140731415577672 140731415577704
In [ ]:
In [1]:
# # # Fundamental Data Types :-
# int, float, complex, bool, str
# # # Immutability
In [4]:
# # # Immutability Concept :-
In [5]:
# PVM ==> Intelligent
In [3]:
a = 10
b = 10
c = 10
print(id(a))
print(id(b))
print(id(c))
140709893870664 140709893870664 140709893870664
In [6]:
# With Immutability :-
# 1. Memory utilization will be improved.
# 2. Performace also will be improved.
In [6]:
a = 10.5
b = 10.5
print(id(a))
print(id(b))
print(a is b)
2189640694544 2189669176080 False
In [13]:
a = 10
b = 10
print(id(a))
print(id(b))
print(a is b)
140731415577672 140731415577672 True
In [15]:
a = 256
b = 256
print(id(a))
print(id(b))
print(a is b)
140731415585544 140731415585544 True
In [16]:
a = 257
b = 257
print(id(a))
print(id(b))
print(a is b)
2189662697680 2189669186096 False
In [8]:
a = True
b = True
print(id(a))
print(id(b))
print(a is b)
140731414104640 140731414104640 True
In [9]:
a = 'hi'
b = 'hi'
print(id(a))
print(id(b))
print(a is b)
2189573497072 2189573497072 True
In [17]:
a = 10+20j
b = 10+20j
print(id(a))
print(id(b))
print(a is b)
2189669171984 2189669185744 False
In [ ]:
# # Note :- For Previous Python Versions ==>
# For two different variables(a, b) id will be same except for float type and complex type.
# For new Python Versions ==>
# For two different variables(a, b) id will be same for all type.
In [17]:
# Search for an object is available or not?
In [18]:
# Immutability :-
# Once we creates an object, we cannot change content of that object.
# If we are trying to change, with those changes a new object wil be created.
In [23]:
# Till how much value reuse can be done?
# int ==> 0 to 256
In [29]:
l = [10, 20, 30, 40]
print(l)
print(id(l))
l[0] = 7777
print(l)
print(id(l))
[10, 20, 30, 40] 1597873346176 [7777, 20, 30, 40] 1597873346176
In [30]:
# If variavble is saved in stack and object in heap, then ID of v1, v2, v3 etc should be different from object ' HYDERABAD' itself..
# How would we check ID or addreass of variable itself?
# id(v1) --> Address of object pointed by v1
# id(v2)
In [31]:
# # Note :- All Fundamental Data Types are Immutable.
# ex. int, float, bool, complex, str
In [18]:
l1 = [10, 20, 30, 40]
l2 = l1
print(l1)
print(l2)
l1[0] = 777
print(l1)
print(l2)
l2[1] = 888
print(l1)
print(l2)
print(id(l1))
print(id(l2))
print(l1 is l2)
[10, 20, 30, 40] [10, 20, 30, 40] [777, 20, 30, 40] [777, 20, 30, 40] [777, 888, 30, 40] [777, 888, 30, 40] 2189669521536 2189669521536 True
In [19]:
l1 = [10, 20, 30, 40]
l2 = [10, 20, 30, 40]
print(l1)
print(l2)
print(id(l1))
print(id(l2))
print(l1 is l2)
[10, 20, 30, 40] [10, 20, 30, 40] 2189669519232 2189669540416 False
In [40]:
# # # Collection Related Data Types :-
In [41]:
a = 10
b = 10.5
c = True
d = 'durga'
In [42]:
name = 'durga'
names = ['durga', 'ravi', 'shiva']
In [43]:
# Collection Related Data Types :-
# list
# tuple
# set
# frozenset
# dict
# bytes
# bytearray
# range
In [ ]:
# [] ==> list
# () ==> tuple
# {} ==> set
# {100:'durga', 200:'ravi'} ==> dict
In [46]:
# # list :-
In [47]:
# If we want to represent a group of values as a single entity where insertoion oreder preserved and duplicates are allowed.
In [49]:
list = [10, 10.5, 'durga', True, 10, 10, 10.5]
list
Out[49]:
[10, 10.5, 'durga', True, 10, 10, 10.5]
In [69]:
# Properties of List :-
# 1. Insertion order preserved.
# 2. Duplicates are allowed.
# 3. Heterogeneous objects are alllowed.
# 4. Values should be enclosed within [].
# 5. Index and slice are applicable.
# 6. Growable in nature.
# 7. Mutable
In [54]:
list[0]
Out[54]:
10
In [57]:
list[-1]
Out[57]:
10.5
In [58]:
list[2:5]
Out[58]:
['durga', True, 10]
In [60]:
list[0:9:2]
Out[60]:
[10, 'durga', 10, 10.5]
In [61]:
list
Out[61]:
[10, 10.5, 'durga', True, 10, 10, 10.5]
In [62]:
list.append('ravi')
In [63]:
list
Out[63]:
[10, 10.5, 'durga', True, 10, 10, 10.5, 'ravi']
In [64]:
list.append('shiva')
In [66]:
list
Out[66]:
[10, 10.5, 'durga', True, 10, 10, 10.5, 'ravi', 'shiva']
In [67]:
list.remove(10)
In [68]:
list
Out[68]:
[10.5, 'durga', True, 10, 10, 10.5, 'ravi', 'shiva']
In [ ]:
In [57]:
# # Tuple Data Type :-
In [58]:
# It is exactly same as list except that it is immutable
# Read only version of List ==> Tuple
In [59]:
# Tuple Properties :-
# 1. Insertion Order is preserved.
# 2. Indexing and slicing concepts are applicable.
# 3. Duplicates are allowed.
# 4. Heterogenous Objects are allowed.
# 5. ()
# 6. Immutable
# 7. Not Growable
In [60]:
tuple = (10, 20, 30, 40, 10, 'durga', True, 10.5)
tuple
Out[60]:
(10, 20, 30, 40, 10, 'durga', True, 10.5)
In [61]:
tuple[0]
Out[61]:
10
In [62]:
tuple[0:5]
Out[62]:
(10, 20, 30, 40, 10)
In [63]:
tuple[0:6:2]
Out[63]:
(10, 30, 10)
In [64]:
tuple.append(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[64], line 1 ----> 1 tuple.append(10) AttributeError: 'tuple' object has no attribute 'append'
In [94]:
tuple.remove(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[94], line 1 ----> 1 tuple.remove(10) AttributeError: 'tuple' object has no attribute 'remove'
In [93]:
# If content is not fixed and keep om changing ==> List
# Facebook comment: comment
In [84]:
# If content is fixed and won't change ==> Tuple
# Bank account type: Saving or Current
In [85]:
l = [10, 20, 30, 40]
# more memory
In [86]:
t = (10, 20, 30, 40)
# less memory
In [87]:
# Accessing elements is also very fast in Tuple.
# Performance is more for Tuple.
In [88]:
# # Difference b/w List and Tuple : -
# List :-
# 1. Mutable
# 2. [] (Square Brackets)
# 3. More Memory
# 4. Low Performance
# 5. Content not Fixed
# 6. Growable
# 7. Dynamic in Nature
# Tuple :-
# 1. Unmutable
# 2. () (Round Brackets or Parentheses)
# 3. Less Memory
# 4. More Performance
# 5. Content Fixed
# 6. Not Growable
# 7. Static in Nature
In [89]:
t = () # 0 elements
type(t)
Out[89]:
tuple
In [90]:
t = (10) # 1 elements is not tuple untill ',' is not present
type(t)
Out[90]:
int
In [91]:
t = (10,)
type(t)
Out[91]:
tuple
In [92]:
t = (,)
type(t)
Cell In[92], line 1 t = (,) ^ SyntaxError: invalid syntax
In [ ]:
l = [10]
type(l)
Out[ ]:
list
In [ ]:
l = [,]
Cell In[27], line 1 l = [,] ^ SyntaxError: invalid syntax
In [ ]:
t = 10,20,30,40
type(t)
Out[ ]:
tuple
In [ ]:
# In case of Tuple Parantheses are optional
In [ ]:
t = 10
type(t)
Out[ ]:
int
In [ ]:
t = 10,
type(t)
Out[ ]:
tuple
In [ ]:
# # Set Data Type :-
In [ ]:
# Properties of Set:-
# 1. Dupicates are not allowed
# 2. Order is not Important
# 3. Indexing and Slicing concepts are not applicable
# 4. Heterogeneous objects are allowed
# 5. Mutable
# 6. Growable
# 7. {}
In [ ]:
set = {10,20,-30,'durga','apple',10.5,10,20,10.5,'durga','shyam'}
set
Out[ ]:
{-30, 10, 10.5, 20, 'apple', 'durga', 'shyam'}
In [ ]:
type(set)
Out[ ]:
set
In [ ]:
# Examplpe -->
# sms sending application:
# sms for unique numbers in any order
In [ ]:
for x in set:
print(x)
-30 10.5 20 apple shyam 10 durga
In [ ]:
set.append(50)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[48], line 1 ----> 1 set.append(50) AttributeError: 'set' object has no attribute 'append'
In [ ]:
set.add(50)
In [ ]:
set
Out[ ]:
{-30, 10, 10.5, 20, 50, 'apple', 'durga', 'shyam'}
In [ ]:
set.remove('durga')
set
Out[ ]:
{-30, 10, 10.5, 20, 50, 'apple', 'shyam'}
In [ ]:
# Difference b/w List and Set :-
# List :-
# 1. Duplicates Allowed
# 2. Order preserved
# 3. Indexing and Slicing Concepts are applicable
# 4. []
# Set :-
# 1. Duplicates Not Allowed
# 2. Order not preserved
# 3. Indexing and Slicing Concepts are not applicable
# 4. {}
In [1]:
# # Note :- How to Create Empty Set
s = {}
print(type(s)) # beacuse dict is most common used
s = set()
print(type(s)) # set
print(len(s)) # 0
print(s) # set()
<class 'dict'> <class 'set'> 0 set()
In [ ]:
# # Frozenset :-
In [ ]:
# It is exactly same as set except that it is immutable.
In [ ]:
s = {10,20,30,'durga',10.5,True,10,False}
s
Out[ ]:
{10, 10.5, 20, 30, False, True, 'durga'}
In [ ]:
type(s)
Out[ ]:
set
In [ ]:
fs = frozenset(s)
fs
Out[ ]:
frozenset({10, 10.5, 20, 30, False, True, 'durga'})
In [ ]:
type(fs)
Out[ ]:
frozenset
In [ ]:
fs.add(50)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[7], line 1 ----> 1 fs.add(50) AttributeError: 'frozenset' object has no attribute 'add'
In [ ]:
fs.remove(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[8], line 1 ----> 1 fs.remove(10) AttributeError: 'frozenset' object has no attribute 'remove'
In [ ]:
In [1]:
# # dict Data Type :-
In [2]:
# list ==> [10, 20, 30, 40]
# tuple ==> (10, 20, 30, 40)
# set ==> {10, 20, 30, 40}
# frozenset ==> frozenset({10, 20, 30, 40})
# All these data types can hold individual values.
# key-value pairs are
# rollno --> name
# name --> mail id
In [3]:
# dict --> dictionary
# [] --> list
# () --> tuple
# {} --> set
# {} --> dict
In [5]:
d = {100:'durga', 200:'ravi', 300:'shiva'}
print(d)
print(type(d))
{100: 'durga', 200: 'ravi', 300: 'shiva'}
<class 'dict'>
In [6]:
d = {}
print(type(d))
<class 'dict'>
In [12]:
d = {}
print(d)
{}
In [13]:
# d[key] = value
d[100] = 'sunny'
d[200] = 'bunny'
d[300] = 'chinny'
print(d)
{100: 'sunny', 200: 'bunny', 300: 'chinny'}
In [14]:
print(d[100])
sunny
In [15]:
# Properties of dictionary DataType :-
# 1. Order is not preserved
# 2. Indexing and Slicing concepts are not applicable
# 3. For keys and values we can use any data type no restrictions.
# 4. keys and values can be hetrogeneous
# 5. duplicate keys are not allowed but values can be duplicate
# 6. If we are trying to add entry with duplicate key, then old value will be replaced with new value
# 7. Mutable
In [16]:
d = {100:'ravi', 'durga':200}
print(d)
{100: 'ravi', 'durga': 200}
In [17]:
d = {a:'durga', b:'abhi'}
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[17], line 1 ----> 1 d = {a:'durga', b:'abhi'} NameError: name 'a' is not defined
In [19]:
a = 100
b = 200
d = {a:'durga', b:'abhi'}
print(d)
{100: 'durga', 200: 'abhi'}
In [20]:
d = {100:'durga', 200:'ravi'}
# keys: 100, 200
# values: 'durga', 'rqavi'
In [22]:
d = {100:'ravi', 200:'durga', 100:'durga', 200:'ravi'}
print(d)
{100: 'durga', 200: 'ravi'}
In [23]:
d = {100:'durga'}
print(d)
d[100] = 'ravi'
print(d)
{100: 'durga'}
{100: 'ravi'}
In [24]:
d = {100:['durga', 'ravi', 'shiva']}
print(d)
{100: ['durga', 'ravi', 'shiva']}
In [25]:
d = {100:'abc', '100':'xyz'}
print(d)
{100: 'abc', '100': 'xyz'}
In [26]:
# # Range Data Type :-
In [31]:
# range means sequence of values
# 0 to 9
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
In [32]:
r = range(10)
print(r)
print(type(r))
range(0, 10) <class 'range'>
In [33]:
for x in r:
print(x)
0 1 2 3 4 5 6 7 8 9
In [60]:
# Properties of Range Data Type :-
# Sequence
# form-1:
# range(n) ==> 0 to n-1 values can be represented
# form-2:
# range(begin, end) ==> from begin value to end-1
# form-3:
# range(begin, end, increment/decrement value) ==> from begin value to end-1 and increment/decrement
# Indexing and slicing also applicable
# Immutable
In [61]:
r = range(2,8)
for x in r:
print(x)
2 3 4 5 6 7
In [62]:
r = range(1,11)
for x in r:
print(x)
1 2 3 4 5 6 7 8 9 10
In [63]:
r = range(1,11,2)
for x in r:
print(x)
1 3 5 7 9
In [64]:
r = range(11,1,-2)
for x in r:
print(x)
11 9 7 5 3
In [65]:
r = range(1,11,3)
for x in r:
print(x)
1 4 7 10
In [66]:
l = []
r = range(0,101,5)
for x in r:
l.append(x)
print(l)
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
In [67]:
r = range(1,11,-1)
for x in r:
print(x)
In [68]:
r = range(10)
print(r)
print(r[0])
range(0, 10) 0
In [69]:
print(r[2])
2
In [70]:
print(r[5])
5
In [71]:
print(r[-1])
9
In [72]:
print(r[2:5])
range(2, 5)
In [73]:
print(r[2:8:2])
range(2, 8, 2)
In [74]:
r[1] = 7777
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[74], line 1 ----> 1 r[1] = 7777 TypeError: 'range' object does not support item assignment
In [75]:
# # bytes Data Type :-
In [76]:
# If we want tot represent a group of values within the range 0 to 255
In [ ]:
# Properties of byte Data Type :-
# 1. Indexing and slicing applicable
# 2. Values should be in range 0 to 255
# 3. Immutable
# 4. b = bytes()
In [78]:
l = [10, 20, 30, 40]
b = bytes(l)
print(type(b))
print(b)
<class 'bytes'>
b'\n\x14\x1e('
In [79]:
l = [10, 20, 30, 40, 256]
b = bytes(l)
print(type(b))
print(b)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[79], line 3 1 l = [10, 20, 30, 40, 256] ----> 3 b = bytes(l) 5 print(type(b)) 6 print(b) ValueError: bytes must be in range(0, 256)
In [80]:
print(b[0])
10
In [81]:
print(b[2])
30
In [82]:
print(b[-1])
40
In [84]:
for x in bytes[1:3]:
print(x)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[84], line 1 ----> 1 for x in bytes[1:3]: 2 print(x) TypeError: type 'bytes' is not subscriptable
In [85]:
for x in b[1:3]:
print(x)
20 30
In [86]:
l = [10, 20, 30, 40]
b = bytes(l)
b[0] = 777
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[86], line 5 1 l = [10, 20, 30, 40] 3 b = bytes(l) ----> 5 b[0] = 777 TypeError: 'bytes' object does not support item assignment
In [89]:
# list --> mutable
# tuple --> immutable
# set --> mutable
# frozenset --> immutable
# dict --> mutable
# range --> immutable
# bytes --> immutable
# bytearray --> mutable
In [90]:
# # bytearray Data Type :-
In [91]:
# It is exactly same as bytes except that it is mutable.
In [92]:
l = [10, 20, 30, 40]
b = bytearray(l)
print(type(b))
<class 'bytearray'>
In [93]:
l = [10, 20, 30, 40, 256]
b = bytearray(l)
print(type(b))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[93], line 3 1 l = [10, 20, 30, 40, 256] ----> 3 b = bytearray(l) 5 print(type(b)) ValueError: byte must be in range(0, 256)
In [94]:
l = [10, 20, 30, 40]
b = bytearray(l)
b[0] = 15
In [96]:
for x in b:
print(x)
15 20 30 40
In [ ]:
In [1]:
# # Data Types :-
In [2]:
# int flaot complex bool str
# list tuple
# set frozenset
# dict
# range
# bytes bytearray
In [3]:
# 1. In general bytes and bytearray types can be used to represent binary information like images, video files etc.
# 2. Long data type avaliable in Python2x but not in Python3x long values also can be represented as int type only
# 3. char data type 'a' as str type
In [4]:
# # None Data Type :-
In [11]:
# None means nothing or no value associated.
# If the value is not available, to handle such type of requirements None (null in Java)
# None --> no value associated
# None is also an object in Python
x = None
print(x)
print(id(x))
print(type(x))
None 140731371719440 <class 'NoneType'>
In [12]:
def f1():
return 10
r = f1()
print(r)
10
In [13]:
def f1():
print('hello')
r = f1()
print(r)
hello None
In [14]:
# Only one None value will be created in python
In [16]:
a = None
b = None
c = None
def f1():
pass
r = f1()
print(a)
print(id(a))
print(type(a))
print(b)
print(id(b))
print(type(b))
print(c)
print(id(c))
print(type(c))
print(r)
print(id(r))
print(type(r))
None 140731371719440 <class 'NoneType'> None 140731371719440 <class 'NoneType'> None 140731371719440 <class 'NoneType'> None 140731371719440 <class 'NoneType'>
In [17]:
# # Escape Characters :-
In [52]:
# The characters associated with some special meaning
# \n --> New Line
# \t --. Horizontal Tab
# \r --> Carriage Return
# \b --> Backspace
# \f --. Form Feed
# \v --> Vertical Tab
# \' --> Single Quote
# \" --> Double Quote
# \\ --> Backslash Symbol
# etc
In [53]:
s = 'durga\tsoft'
print(s)
durga soft
In [54]:
s = 'durga\nsoft'
print(s)
durga soft
In [55]:
s = 'durga\rtsoft'
print(s)
tsoft
In [56]:
s = 'durga\bsoft'
print(s)
durgsoft
In [57]:
s = 'durga\fsoft'
print(s)
durga soft
In [58]:
s = 'durga\vsoft'
print(s)
durga soft
In [59]:
s = 'durga\'sof\'t'
print(s)
durga'sof't
In [60]:
s = 'durga\"sof\"t'
print(s)
durga"sof"t
In [61]:
s = 'C:\\Python\\Practice'
In [62]:
# # Comments :-
In [63]:
# Single Line Comment:
# This is code
s = 'pulkit' # code output: 'pulkit'
In [64]:
# Multi-Line Comment:
# There is no special symbol for multiline comments
'''
This is
Multi-Line
Comment
''' # This is Documentation String but not Comment
"""
This is
Multi-Line
Comment
""" # This is Documentation String but not Comment
s = 'pulkit'
In [65]:
# Triple Quotes can be used for:-
# 1. To define multiline string literals
# 2. To use ' or " as symbols
# 3. To define docstring
In [66]:
# # Constants :-
In [67]:
# Constants concept not applicable in Python
# MAX_VALUE = 10 # it is constant doesn't change its value
# max_value = 10
In [68]:
MAX_VALUE = 10
print(type(MAX_VALUE))
<class 'int'>
In [ ]:
In [3]:
# set --> unique elements(no duplicates)
# order is not important
s = {10, 20, 30, 40}
s.add(50)
print(s)
{40, 10, 50, 20, 30}
In [4]:
# unique elements(no duplicates)
# order is not important
# frozenset
s = {10, 20, 30, 40}
fs = frozenset(s)
fs.add(50)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[4], line 7 5 s = {10, 20, 30, 40} 6 fs = frozenset(s) ----> 7 fs.add(50) AttributeError: 'frozenset' object has no attribute 'add'
In [6]:
# bytes and bytearray
# 0 to 255
# bytes --> immutable
# bytearray --> mutable
# images, video files and audio files etc
In [7]:
l = [10, 20, 30, 40]
b = bytes(l)
for x in b:
print(x)
10 20 30 40
In [8]:
b[0] = 50
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 1 ----> 1 b[0] = 50 TypeError: 'bytes' object does not support item assignment
In [9]:
l = [10, 20, 30, 40]
b = bytearray(l)
for x in b:
print(x)
10 20 30 40
In [10]:
b[0] = 50
In [11]:
for x in b:
print(x)
50 20 30 40
In [12]:
print('# this is comment')
# this is comment
# # Operators :-¶
In [16]:
# Telephone Operator
# Camera Operator
# # Types of Operators:-
# 1. Arithmetic Operators
# 2. Relational Operators
# 3. Logical Operators
# 4. Bitwise Operators
# 5. Assignment Operators
# 6. Special Operators
# 1. Arithmetic Operators :-¶
In [39]:
# + --> Addition
# - --> Subtraction
# * --> Multiplication
# / --> Division
# % --> Modulo Operator
# // --> Floor Division Operator
# ** --> Exponent Operator or Power Operator
In [42]:
10+2
Out[42]:
12
In [43]:
10-2
Out[43]:
8
In [44]:
10*2
Out[44]:
20
In [57]:
10%2
Out[57]:
0
In [58]:
# # Note:-
# The result of '/' division operator is always float type
# // result is either int type or float type
# If both arguments are int type result is int type only
# If atleast one argument is float type result is float type
In [66]:
10/2
Out[66]:
5.0
In [59]:
10//2
Out[59]:
5
In [60]:
23/6
Out[60]:
3.8333333333333335
In [69]:
23//6
Out[69]:
3
In [70]:
1.2//2
Out[70]:
0.0
In [71]:
# 1.56 ->
# floor int value ==> 1
# floor float value ==> 1.0
# ceil int value ==> 2
# ceil float value ==> 2.0
In [72]:
10.0/2
Out[72]:
5.0
In [73]:
10.0//2
Out[73]:
5.0
In [74]:
10/3
Out[74]:
3.3333333333333335
In [75]:
10//3
Out[75]:
3
In [78]:
10.0/3
Out[78]:
3.3333333333333335
In [79]:
10.0//3
Out[79]:
3.0
In [80]:
# * --> multiplication
# ** --> exponential or power
In [83]:
10**3 # 10 * 10 * 10
Out[83]:
1000
In [84]:
3**3 # 3 * 3 * 3
Out[84]:
27
In [85]:
3***3
Cell In[85], line 1 3***3 ^ SyntaxError: invalid syntax
In [86]:
3.0**3
Out[86]:
27.0
In [88]:
3**3*2
Out[88]:
54
In [89]:
10**-3
Out[89]:
0.001
In [90]:
10**2.8
Out[90]:
630.957344480193
In [91]:
3//2
Out[91]:
1
In [92]:
# + and * :-
# + operator applicable for str type also
# concatenation operator
In [94]:
s = 'durga' + 'soft'
print(s)
durgasoft
In [96]:
'durga' + str(10)
Out[96]:
'durga10'
In [97]:
int('durga')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[97], line 1 ----> 1 int('durga') ValueError: invalid literal for int() with base 10: 'durga'
In [99]:
'durga' + 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[99], line 1 ----> 1 'durga' + 10 TypeError: can only concatenate str (not "int") to str
In [100]:
# Problem with Value ValueError
# Problem with Type TypeError
In [101]:
'durga' * 3
Out[101]:
'durgadurgadurga'
In [102]:
'durga' * 'durga'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[102], line 1 ----> 1 'durga' * 'durga' TypeError: can't multiply sequence by non-int of type 'str'
In [106]:
'durga' * int('10')
Out[106]:
'durgadurgadurgadurgadurgadurgadurgadurgadurgadurga'
In [107]:
# + --> both arguments should be str type or int type
# * --> one arg str and one arg int
In [109]:
'durga' * 10.0
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[109], line 1 ----> 1 'durga' * 10.0 TypeError: can't multiply sequence by non-int of type 'float'
In [110]:
10/0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[110], line 1 ----> 1 10/0 ZeroDivisionError: division by zero
In [111]:
10.0/0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[111], line 1 ----> 1 10.0/0 ZeroDivisionError: float division by zero
In [112]:
'abc' * 0
Out[112]:
''
# 2. Relational Operators :-¶
In [114]:
# <, <=, >, >=
In [116]:
a = 10
b = 20
In [117]:
a < b
Out[117]:
True
In [118]:
a <= b
Out[118]:
True
In [119]:
a > b
Out[119]:
False
In [120]:
a >= b
Out[120]:
False
In [122]:
# string values also comparison is bsaed on unicode value/ascii value
# a --> 97
# b --> 98
# c --> 99
# A --> 65
# B --> 66
# C --> 67
In [123]:
a = 'durga'
b = 'ravi'
In [124]:
a < b
Out[124]:
True
In [125]:
a <= b
Out[125]:
True
In [126]:
a > b
Out[126]:
False
In [127]:
a >= b
Out[127]:
False
In [128]:
a = 'durga'
b = 'Durga'
In [129]:
a < b
Out[129]:
False
In [130]:
a <= b
Out[130]:
False
In [131]:
a > b
Out[131]:
True
In [132]:
a >= b
Out[132]:
True
In [135]:
ord('d')
Out[135]:
100
In [136]:
ord('D')
Out[136]:
68
In [137]:
ord('a') * ord('b')
Out[137]:
9506
In [138]:
ord('a') + ord('b')
Out[138]:
195
In [144]:
# from char find ascii value
# ord()
# from ascii value to char value
# chr()
# char --> ord()
# ascii --> chr()
In [140]:
chr(99)
Out[140]:
'c'
In [141]:
chr(10)
Out[141]:
'\n'
In [143]:
chr(72) + chr(99)
Out[143]:
'Hc'
In [145]:
# for boolean types
# True --> 1
# Fasle -->
In [146]:
a = True
b = False
In [147]:
a > b
Out[147]:
True
In [148]:
a >= b
Out[148]:
True
In [149]:
a < b
Out[149]:
False
In [150]:
a <= b
Out[150]:
False
In [151]:
'durga' < 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[151], line 1 ----> 1 'durga' < 10 TypeError: '<' not supported between instances of 'str' and 'int'
In [153]:
a = True
b = 10
In [154]:
a > b
Out[154]:
False
In [155]:
a < b
Out[155]:
True
In [156]:
2**2 < 5
Out[156]:
True
In [157]:
2**2 > 5
Out[157]:
False
In [158]:
'a' > '297'
Out[158]:
True
In [160]:
ord('a')
Out[160]:
97
In [161]:
ord('2')
Out[161]:
50
In [163]:
ord('a') > ord('2')
Out[163]:
True
In [164]:
10 < 20
Out[164]:
True
In [165]:
10 < 20 < 30
Out[165]:
True
In [166]:
10 < 20 < 30 < 40
Out[166]:
True
In [167]:
10 < 20 < 30 < 40 > 50
Out[167]:
False
In [184]:
# Chaning of Relational Operators:-
# If all comparison returns True then the result is True.
# If atleast one comparison returns False then the result is False.
# Equality Operators :-¶
In [3]:
# == and !=
# always meant for content comparosion
In [4]:
10 == 20
Out[4]:
False
In [5]:
10 == 10
Out[5]:
True
In [6]:
10.5 == 10
Out[6]:
False
In [7]:
10.0 == 10
Out[7]:
True
In [8]:
'durga' == 'ravi'
Out[8]:
False
In [9]:
'durga' == 10
Out[9]:
False
In [10]:
True == False
Out[10]:
False
In [11]:
True == 1
Out[11]:
True
In [12]:
ord('d')
Out[12]:
100
In [13]:
'd' == 100
Out[13]:
False
In [17]:
ord('d') == 100
Out[17]:
True
In [14]:
# == --> operator for content comparosion
# = --> means assignment
In [15]:
True == 1.0
Out[15]:
True
In [16]:
ord('a') == 97
Out[16]:
True
In [18]:
# Chaning of Equality Operators:-
# If all comparison returns True then the result is True.
# If atleast one comparison returns False then the result is False.
In [19]:
10 == 20 == 30 == 40
Out[19]:
False
In [20]:
10 == 10.0 == 10 == 10.0
Out[20]:
True
In [21]:
1 == 1.0 == True == 1.0
Out[21]:
True
# == operator and is operator¶
In [22]:
# == operator meant for content comparosion
# is operator meant for reference comparosion(address comparison)
# is operator returns True if both refrences are pointing to the same object address.
In [25]:
l1 = [10, 20, 30, 40]
l2 = [10, 20, 30, 40]
print(id(l1))
print(id(l2))
print(l1 is l2)
print(l1 == l2)
1444155477056 1444155379712 False True
In [26]:
l1 = [10, 20, 30, 40]
l2 = l1
print(id(l1))
print(id(l2))
print(l1 is l2)
print(l1 == l2)
1444155476352 1444155476352 True True
# 3. Logical Operators :-¶
In [27]:
# and
# or
# not
In [28]:
# For boolean Types :-
# and --> If both arguments are True then only result is True
# or --> If atleast one argument is True then result is True
# not --> complement
In [29]:
True and True
Out[29]:
True
In [30]:
True and False
Out[30]:
False
In [31]:
False and True
Out[31]:
False
In [32]:
False and False
Out[32]:
False
In [33]:
not True
Out[33]:
False
In [34]:
not False
Out[34]:
True
In [35]:
True or True
Out[35]:
True
In [36]:
True or False
Out[36]:
True
In [37]:
False or True
Out[37]:
True
In [38]:
False or False
Out[38]:
False
In [42]:
# For non-Boolean Types :-
# zero consider as False
# non-zero consider as True
# empty string, set, list, tuple etc considered as False
# non-empty considered as True
# For non-Boolean Types we are not getting True or False.
In [43]:
# and Operator :-
# x and y ->
# if x evalutes to True then the result is y
# if x evalutes to False then the result is x
In [44]:
10 and 20
Out[44]:
20
In [45]:
0 and 10
Out[45]:
0
In [46]:
'' and 10
Out[46]:
''
In [47]:
'as' and 10
Out[47]:
10
In [48]:
# or Operator :-
# x or y ->
# If x evaluates to True then the result is x
# If x evaluates to False then the result is y
In [49]:
10 or 20
Out[49]:
10
In [50]:
0 or 10
Out[50]:
10
In [51]:
10 or 0
Out[51]:
10
In [52]:
'' or 'durga'
Out[52]:
'durga'
In [53]:
'durga' or ''
Out[53]:
'soft'
In [54]:
0 or 0
Out[54]:
0
In [1]:
not 10
Out[1]:
False
In [2]:
not ''
Out[2]:
True
In [3]:
not 0
Out[3]:
True
In [4]:
not 'durga'
Out[4]:
False
In [ ]:
# 4. Bitwise Operators :-¶
In [5]:
# & --> AND
# | --> OR
# ^ --> X-OR
# ~ --> Bitwise Complement Operator
# << --> Left Shift Operator
# >> --> Right Shift Operator
# Applicable only for:-
# int type and boolean type
In [2]:
10 & 11
Out[2]:
10
In [3]:
True & False
Out[3]:
False
In [4]:
10.5 & 11.6
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 1 ----> 1 10.5 & 11.6 TypeError: unsupported operand type(s) for &: 'float' and 'float'
In [6]:
# & --> If both bits are 1 then result is 1
# | --> If atleast one bit is 1 then result is 1
# ^ --> If both bits are different then result is 1
# if both bits are same then result is 0
In [11]:
a = 4 # 4 --> 1 0 0
b = 5 # 5 --> 1 0 1
a & b # 1 0 0
Out[11]:
4
In [12]:
a = 4 # 4 --> 1 0 0
b = 5 # 5 --> 1 0 1
a | b # 1 0 1
Out[12]:
5
In [13]:
a = 4 # 4 --> 1 0 0
b = 5 # 5 --> 1 0 1
a ^ b # 0 0 1
Out[13]:
1
In [14]:
# Bitwise Complement Operator(~) :-
In [19]:
~4
Out[19]:
-5
In [16]:
~9
Out[16]:
-10
In [17]:
~-5
Out[17]:
4
In [18]:
~-20
Out[18]:
19
In [20]:
# 32 bits
# The most significant bit(MSB) acts as sign bit
# 0 means +ve number
# 1 means -ve number
# positive numbers will be represented directly in the memory
# But negative numbers will be represented indirectly in the memory in 2's complement form
# 2's complement form = 1's complement form+1
# 1's complement form = intrchange 0s and 1s
In [22]:
# 4 = 0000000000.....000000100
# ~4 = 1111111111.....111111011 ==> -5
In [23]:
# Shift Operators :-
In [24]:
# << and >>
# << --> Left Shift
# >> --> Right Shift
In [32]:
# << --> Left Shift :-
# extra cells are always filled with zero
In [37]:
10 << 2
# 10 --> 00000000000....0000000001010
# 10<< --> 000000000....0000000101000
Out[37]:
40
In [28]:
4 << 2
# 4 --> 00000000000....0000000000100
# 4<< --> 000000000....0000000010000
Out[28]:
16
In [33]:
# >> --> Right Shift :-
# extra cells are always filled with sign bit
# +ve number zero(0)
# -ve number one(1)
In [34]:
10 >> 2
# 10 --> 00000000000....0000000001010
# 10>> --> 00000000000000000....000000010
Out[34]:
2
In [35]:
4 >> 2
# 4 --> 00000000000....0000000000100
# 4<< --> 00000000000000000....000000001
Out[35]:
1
In [41]:
-10 >> 2
# 10 --> 00000000000....0000000001010
# 1's complement --> 11111111111....1111111110101
# 1
# 2's complement --> 11111111111....1111111110110
# -10 --> 11111111111....1111111110110
# -10>> --> 111111111111111....11111111101 # -ve as first value is 1
# 2's complement --> 000000000000000....00000000010
# 1
# --> 000000000000000....00000000011
# Value is -ve so ans is -3
Out[41]:
-3
In [38]:
10 >> -3
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[38], line 1 ----> 1 10 >> -3 ValueError: negative shift count
In [42]:
True & True
Out[42]:
True
In [43]:
True | True
Out[43]:
True
In [44]:
True ^ False
Out[44]:
True
In [45]:
False ^ True
Out[45]:
True
In [46]:
~True
Out[46]:
-2
In [47]:
~False
Out[47]:
-1
In [49]:
True >> 2
Out[49]:
0
In [50]:
False >> 2
Out[50]:
0
In [51]:
True << 2
Out[51]:
4
In [52]:
False << 2
Out[52]:
0
In [53]:
False << 4
Out[53]:
0
In [54]:
False << 4
Out[54]:
0
In [ ]:
# 5. Assignment Operators :-¶
In [6]:
# assignment combined with some other operators: compound assignment operator
# +=
# -=
# *=
# /=
# %=
# //=
# **=
# &=
# |=
# ^=
# >>=
# <<=
In [7]:
x = 10
print(x)
x += 20
print(x)
10 30
In [8]:
x = 4
print(x)
x **= 2
print(x)
4 16
In [9]:
x = 4
print(x)
x &= 5
print(x)
4 4
In [36]:
x = 10
print(x)
x++
print(x)
Cell In[36], line 3 x++ ^ SyntaxError: invalid syntax
In [37]:
x = 10
print(x)
++x
print(x)
10 10
In [38]:
x = 10
print(x)
++++x
print(x)
10 10
In [39]:
x = 10
print(x)
--x
print(x)
10 10
In [40]:
x = 10
print(x)
---x
print(x)
10 10
In [41]:
x = 10
print(x)
x =+ x
print(x)
10 10
In [42]:
x = 10
print(x)
x =+ x
print(x)
x = x
print(x)
10 10 10
In [43]:
x = 10
print(x)
x =-- x
print(x)
10 10
In [44]:
x = 10
print(x)
x =--- x
print(x)
10 -10
In [45]:
# # How to handle increment and decrement in python
In [46]:
x = 10
print(x)
x = x+1
print(x)
10 11
In [47]:
x = 10
print(x)
x += 1
print(x)
10 11
In [48]:
x = 10
print(x)
x = x-1
print(x)
10 9
In [49]:
x = 10
print(x)
x -= 1
print(x)
10 9
# Ternary Operator or Conditional Operator :-¶
In [50]:
# Unary Operators :-
# ~x
# not x
In [51]:
# Binary Operators :-
# a+b
# a*b
In [52]:
# Ternary Operator or Conditional Operator :-
# a,b = 10,20
# x = 30 if a<b else 40
# x = first value if condition else second value
In [53]:
a,b = 10,20
x = 30 if a<b else 40
print(x)
30
In [59]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
min = a if a < b else b
print('Minimum Value:', min)
Minimum Value: 2
In [64]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
c = int(input('Enter Third Number: '))
min = a if a<b and a<c else b if b<c else c
print('Minimum Value:', min)
Minimum Value: 12
In [65]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
c = int(input('Enter Third Number: '))
min = a if a>b and a>c else b if b>c else c
print('Maximum Value:', min)
Minimum Value: 99
In [66]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
s1 = 'Both Number are Equal'
s2 = 'First Number is greater than Second Number'
s3 = 'First NUmber is less than Second Number'
result = s1 if a==b else s2 if a>b else s3
print(result)
Both Number are Equal
In [67]:
max(10, 20, 50, 90, 30, 500, 450, 160, 420, 390)
Out[67]:
500
# 6. Special Operators :-¶
In [71]:
# Special Operators :-
# 1. Identity Operator
# 2. Membership Operator
In [72]:
# 1. Identity Operator
# is
# is not
# Example:
# r1 is r2 retruns True if both refrences are pointing to the same address
# r1 is not r2 retruns True if both refrences are not pointing to the same object
In [73]:
a = 10
b = 10
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
140731373110344 140731373110344 True False
In [74]:
a = 10
b = 20
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
140731373110344 140731373110664 False True
In [77]:
a = [10,20,30,40]
b = [10,20,30,40]
print(id(a))
print(id(b))
print(a is b)
print(a == b)
print(a is not b)
1772942460224 1772942011136 False True True
In [78]:
a = [10,20,30,40]
b = a
print(id(a))
print(id(b))
print(a is b)
print(a == b)
print(a is not b)
1772948496768 1772948496768 True True False
In [79]:
# 2. Membership Operator :-
# given object present in the given collection or not
# collection can be --> string, list, tuple, set, dict etc
# obj in collection ==> if obj is member of collection returns True
# not in collection ==> if obj is not member of collection returns True
In [80]:
x = 'hello learning python is very easy!!!'
In [81]:
'h' in x
Out[81]:
True
In [82]:
'd' in x
Out[82]:
False
In [83]:
'd' not in x
Out[83]:
True
In [84]:
'python' in x
Out[84]:
True
In [85]:
'python' not in x
Out[85]:
False
In [86]:
list = ['sunny', 'bunny', 'chinny', 'vinny']
In [87]:
'bunny' in list
Out[87]:
True
In [88]:
'buuny' in list
Out[88]:
False
In [89]:
10+20*3
Out[89]:
70
# Python Operator Precedence :-¶
In [91]:
# ()
# **
# ~,-(unary minus)
# *, /, %, //
# +, -
# <<, >>
# &
# ^
# |
# >, >=, <, <=, ++, !=
# =, +=, -=, *=, ...
# is, is not
# in, in not
# not
# and
# or
In [92]:
a = 30
b = 20
c = 10
d = 5
In [93]:
(a+b)*c/d
Out[93]:
100.0
In [94]:
(a+b)*(c/d)
Out[94]:
100.0
In [95]:
a+(b*c)/d
Out[95]:
70.0
In [ ]:
In [2]:
# # # Mathematical Functions by using Math Module :-
In [3]:
# Library Contains ---> a group of packages
# Package Contains ---> a group of modules
# Module Contains ---> a group of functions, variables, classes etc
In [4]:
# Module name: durgamath
# import durgamath
# short alias name
# import durgamath as dm
In [ ]:
# from durgamath as dm
# print(dm.PI)
# print(dm.name)
# dm.add(10,20)
# dm.multiply(10,20)
# s = dm.Student()
# s.activity()
In [5]:
# # Note :-
# Once we defined alias name, we cannot use original name.
In [ ]:
# from durgamath as dm
# print(durgamath.PI)
# print(dm.name)
# dm.add(10,20)
# dm.multiply(10,20)
# s = dm.Student()
# s.activity()
# It will show error
In [ ]:
# Access memebers directly without module name???
# from durgamath import PI
In [6]:
# from durgamath import PI, name
# print(PI)
# print(name)
# add(10,20)
# multiply(10,20)
# s = Student()
# s.activity()
# In this only PI and name are available
In [7]:
# from durgamath import *
# print(PI)
# print(name)
# add(10,20)
# multiply(10,20)
# s = Student()
# s.activity()
In [10]:
# Alias name for the members :-
In [9]:
# from durgamath import add as a
# a(100,200)
In [11]:
import math
In [12]:
math.sqrt(16)
Out[12]:
4.0
In [14]:
math.pi
Out[14]:
3.141592653589793
In [15]:
from math import *
In [16]:
sqrt(16)
Out[16]:
4.0
In [17]:
pi
Out[17]:
3.141592653589793
In [18]:
import math as m
In [19]:
m.sqrt(16)
Out[19]:
4.0
In [20]:
m.pi
Out[20]:
3.141592653589793
In [21]:
import math
In [23]:
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
In [25]:
from math import *
print('PI =',pi)
print('E =',e)
print(ceil(10.1))
print(floor(10.1))
PI = 3.141592653589793 E = 2.718281828459045 11 10
In [26]:
from random import randint
In [27]:
randint(0,9)
Out[27]:
5
In [28]:
randint(0,9)
Out[28]:
2
In [29]:
from random import *
In [30]:
randint(0,9)
Out[30]:
3
In [ ]:
# # Input and Output Statements :-¶
# Input Statements :-¶
In [2]:
# To read dynamic input from the keyboard :-
# 1. raw_input()
# 2. input()
In [3]:
# 1. raw_input() :-
# x = raw_input('Enter some value:')
# print(type(x)) # str type only
# i = int(x)
# Typecasting is required
In [4]:
# 2. input() :-
# x = input('Enter some value:')
# print(type(x)) # the result need not be str type
# Typecasting is not required
In [5]:
# This story is not appl only for Python-2 but not for Python-3
In [6]:
# In Python-3, we have only input() function but not raw_input() function.
# Python-3 input() function ==> Python-2 raw_input() function
# In Python-3 input() function always returns str type only.
# We have to perform typcasting.
In [7]:
# 100 objects ==> minimum 90% of objects are string type only
# 10% requirement ==> typecasting functions are there
In [8]:
x = input('Enter some value: ')
print(type(x))
<class 'str'>
In [9]:
x = int(input('Enter some value: '))
print(type(x))
<class 'int'>
In [10]:
# # String to Other Types :-
In [16]:
# Type casting functions are required
# Type casting ==> Type Conversion
# str --> int type ==> int(str)
# str --> float type ==> float(str)
# str --> boolean type ==> boolean(str)
# str --> complex type ==> complex(str)
In [19]:
x = input('Enter some value: ')
i = int(x)
print(type(i))
<class 'int'>
In [20]:
x = input('Enter some value: ')
i = float(x)
print(type(i))
<class 'float'>
In [14]:
x = input('Enter some value: ')
i = bool(x)
print(type(i))
<class 'bool'>
In [15]:
x = input('Enter some value: ')
i = complex(x)
print(type(i))
<class 'complex'>
In [21]:
x = input('Enter First Number: ')
y = input('Enter Second Number: ')
x = int(x)
y = int(y)
print('Sum is:', x+y)
Sum is: 6924
In [24]:
x = int(input('Enter First Number: '))
y = int(input('Enter Second Number: '))
print('Sum is:', x+y)
Sum is: 11
In [25]:
eno = int(input('Enter Employee Number: '))
ename = input('Enter Employee Name: ')
esal = float(input('Enter Employee Salary: '))
eaddr = input('Enter Employee Address: ')
married = bool(input('Employee Married?[True|False]: '))
print('Please Confirm your Information:')
print('Employee Number: ', eno)
print('Employee Name: ', ename)
print('Employee Salary: ', esal)
print('Employee Address: ', eaddr)
print('Employee Married: ', married)
Please Confirm your Information: Employee Number: 784 Employee Name: ankd Employee Salary: 4654.0 Employee Address: acef Employee Married: True
In [ ]:
# eval('str')
# eval('10') --> int
# eval('10.5') --> float
# eval('True') --> boolean
# eval('False') --> boolean
In [28]:
eno = int(input('Enter Employee Number: '))
ename = input('Enter Employee Name: ')
esal = float(input('Enter Employee Salary: '))
eaddr = input('Enter Employee Address: ')
married = eval(input('Employee Married?[True|False]: '))
print('Please Confirm your Information:')
print('Employee Number: ', eno)
print('Employee Name: ', ename)
print('Employee Salary: ', esal)
print('Employee Address: ', eaddr)
print('Employee Married: ', married)
Please Confirm your Information: Employee Number: 46 Employee Name: dwf Employee Salary: 45.0 Employee Address: ad Employee Married: False
In [29]:
# # eval() :-
In [30]:
# eval() functin take string as argument and evaluates the result.
In [35]:
x = eval('10+20+30')
print(x)
print(type(x))
60 <class 'int'>
In [36]:
x = int('10+20+30')
print(x)
print(type(x))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[36], line 1 ----> 1 x = int('10+20+30') 2 print(x) 3 print(type(x)) ValueError: invalid literal for int() with base 10: '10+20+30'
In [37]:
x = eval(input('Enter some Value:'))
print(x)
print(type(x))
(10, 10, 51) <class 'tuple'>
In [38]:
x = eval('true')
print(x)
print(type(x))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[38], line 1 ----> 1 x = eval('true') 2 print(x) 3 print(type(x)) File <string>:1 NameError: name 'true' is not defined
In [39]:
x = eval('True')
print(x)
print(type(x))
True <class 'bool'>
In [40]:
x = eval(input('Enter some Value:'))
print(x)
print(type(x))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[40], line 1 ----> 1 x = eval(input('Enter some Value:')) 2 print(x) 3 print(type(x)) File <string>:1 NameError: name 'true' is not defined
In [41]:
# eval() is always taking string argument only, but that string should represent non-string value internally.
In [42]:
x = eval('durga')
print(x)
print(type(x))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[42], line 1 ----> 1 x = eval('durga') 2 print(x) 3 print(type(x)) File <string>:1 NameError: name 'durga' is not defined
In [43]:
x = eval('10')
print(x)
print(type(x))
10 <class 'int'>
In [ ]:
In [4]:
# How to read multiple values from the keyboard in a single line :-
# '10 20 30' ==> a single string which contains int values with space separator
# ['10', '20', '30'] ==> list
In [7]:
s = '10 20 30'
l = s.split()
print(l)
['10', '20', '30']
In [ ]:
# string values to int type ==> int()
In [12]:
s = '10 20 30'
l = s.split()
print(l)
['10', '20', '30']
In [13]:
a, b, c = [10, 20, 30] # unpacking
print(a, b, c)
10 20 30
In [14]:
s = input('Enter two Numbers:')
print(s)
l = s.split()
print(l)
45 65 ['45', '65']
In [15]:
l = input('Enter two Numbers:').split()
print(l)
['65', '46']
In [21]:
a, b = input('Enter two Numbers:').split()
print(a)
print(b)
print(type(a))
print(type(b))
46 654 <class 'str'> <class 'str'>
In [17]:
# for each string present in this list, convert into int value
# list comprehension
In [20]:
a, b = [int(x) for x in input('Enter two Numbers:').split()]
print(a)
print(b)
print(type(a))
print(type(b))
6546 656 <class 'int'> <class 'int'>
In [22]:
a, b = [int(x) for x in input('Enter two Numbers:').split()]
print('Product of two numbers:', a*b)
Product of two numbers: 3936
In [24]:
a, b = [int(x) for x in input('Enter two Numbers:').split(',')]
print('Product of two numbers:', a*b)
Product of two numbers: 1080
In [26]:
a, b, c = [float(x) for x in input('Enter two Numbers:').split('-')]
print('Sum of Numbers:', a+b+c)
Sum of Numbers: 15.0
# Comand Line Arguments :-¶
In [28]:
# The arguments which are passing from the command prompt
# cmd line arguments are always str type only
In [29]:
# python test.py 10 20 30
# sys module
# argv --> list
# contains 4 values
# test.py 10 20 30
# argv[0] --> test.py
# argv[1] --> 10
# argv[2] --> 20
# argv[3] --> 30
In [37]:
from sys import argv\
print(len(argv))
print(argv)
print(type(argv))
2 ['c:\\Users\\pulki\\anaconda3\\envs\\Personal\\Lib\\site-packages\\ipykernel_launcher.py', '--f=c:\\Users\\pulki\\AppData\\Roaming\\jupyter\\runtime\\kernel-v2-15792Rm05Jqyd3e23.json'] <class 'list'>
In [38]:
print(argv[0])
c:\Users\pulki\anaconda3\envs\Personal\Lib\site-packages\ipykernel_launcher.py
In [39]:
for x in argv:
print(x)
c:\Users\pulki\anaconda3\envs\Personal\Lib\site-packages\ipykernel_launcher.py --f=c:\Users\pulki\AppData\Roaming\jupyter\runtime\kernel-v2-15792Rm05Jqyd3e23.json
In [41]:
# Input --> python test.py 10 20 30
# from sys import argv
# x = argv[1:] # ['10', '20', '30']
# sum = 0
# for x1 in x:
# n = int(x1)
# sum = sum + n # sum+=n
# print('The Sum:', sum)
In [ ]:
# 1. space is the separator
# we should use ""
# 2. always str type
# typecasting
# 3. out of range index
# IndexError
In [1]:
# Language Fundamentals
# Operators and Assignments
# Input and Output Statements
# Input Statements
# input()
# command line arguments
# Output Statements
# Output Statements :-¶
In [6]:
# Form-1 :-
# print()
# To print new line character(\n)
In [7]:
print()
In [8]:
print('Hi')
Hi
In [9]:
print('\n')
In [16]:
# Form-2 :-
# print('string')
# In the string we can use escape characters also
# String repeation Operator *
# One argument must be string and other argument must be int
# 'durga' * 3
# 3 * 'durga'
# String concatenation Operator also +
# Both arguments must be strings type:
# 'durga' + 'soft'
In [11]:
print('DURGA\tSOFTWARE\tSOLUTIONS')
DURGA SOFTWARE SOLUTIONS
In [12]:
print('DURGA\nSOFTWARE\nSOLUTIONS')
DURGA SOFTWARE SOLUTIONS
In [14]:
print('DURGA' * 3)
DURGADURGADURGA
In [15]:
print('DURGA' + 'SOFT')
DURGASOFT
In [17]:
print(3 + 'durga' + 3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[17], line 1 ----> 1 print(3 + 'durga' + 3) TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [18]:
print(3 * 'DURGA' + 'SOFT')
DURGADURGADURGASOFT
In [19]:
print('DURGA' + 'SOFT')
print('DURGA' , 'SOFT')
DURGASOFT DURGA SOFT
In [26]:
# Form-3 :-
# print() with sep attribute
# default value for sep attribute: space
# Other than space if you want any other, then we should use "sep" attribute
# separator
In [21]:
a,b,c = 10,20,30
print('The Values are:', a,b,c)
The Values are: 10 20 30
In [23]:
name = 'DURGA'
gf = 'SUNNY'
print('Hello', name, 'Your Girl Friend', gf, 'is too good human being')
Hello DURGA Your Girl Friend SUNNY is too good human being
In [24]:
a,b,c = 10,20,30
print(a,b,c, sep='-')
10-20-30
In [25]:
a,b,c = 10,20,30
print(a,b,c, sep='')
102030
In [28]:
# Form-4 :-
# print() with end attribute
# Other than \n if you want any other character: end attribute
# default value for end attribute: \n
In [34]:
print('Hello')
print('durga')
print('soft')
Hello durga soft
In [36]:
print('Hello', end='*')
print('durga', end=' ')
print('soft')
Hello*durga soft
In [38]:
a,b,c = 10,20,30
print(a,b,c, sep='-', end='###')
print(a,b,c, sep='-')
print('durga')
10-20-30###10-20-30 durga
In [39]:
# Form-5 :-
# print(object)
In [40]:
print(10)
10
In [41]:
print(True)
True
In [42]:
print([10,20,30])
[10, 20, 30]
In [43]:
print((10,20,30))
(10, 20, 30)
In [45]:
# Form-6 :-
# print(formatted string)
# %i --> int
# %d --> int
# %f --> float
# %s --> string type
In [46]:
# print('formatted string' %(variable list))
In [48]:
a = 10
print('a value is %i' %a)
a value is 10
In [49]:
a = 10
b = 20
c = 30
print('a value is %i b value is %i c value is %i' %(a,b,c))
a value is 10 b value is 20 c value is 30
In [50]:
a = 10
b = 20
c = 30
print('a value is %d b value is %d c value is %d' %(a,b,c))
a value is 10 b value is 20 c value is 30
In [51]:
name = 'durga'
l = [10,20,30,40]
print('hello %s... The List of items are %s' %(name, l))
hello durga... The List of items are [10, 20, 30, 40]
In [ ]:
# Form-7 :-
# print() with {}
# {} --> Replacement Operator
In [53]:
name = 'Durga'
salary = 10000
gf = 'Sunny'
In [54]:
print(f'Hello {name}, your salary is {salary}, and your Friend is {gf}')
Hello Durga, your salary is 10000, and your Friend is Sunny
In [58]:
print('Hello {x}, your salary is {y}, and your Friend is {z}'.format(x=name, y=salary, z=gf))
Hello Durga, your salary is 10000, and your Friend is Sunny
In [60]:
print('Hello {0}, your salary is {1}, and your Friend is {2}'.format(name, salary, gf))
Hello Durga, your salary is 10000, and your Friend is Sunny
In [61]:
print('Hello {0}, your salary is {1}, and your Friend is {2}'.format(salary, gf, name))
Hello 10000, your salary is Sunny, and your Friend is Durga
In [62]:
print('Hello {}, your salary is {}, and your Friend is {}'.format(name, salary, gf))
Hello Durga, your salary is 10000, and your Friend is Sunny
In [64]:
print('Hi {0} sal is {1}'.format(0='AA', 1=10000))
Cell In[64], line 1 print('Hi {0} sal is {1}'.format(0='AA', 1=10000)) ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
In [ ]:
In [1]:
# Language Fundamentals
# Operators and Assignments
# Input and Output Statements
# # Flow Control :-¶
In [2]:
# # Flow Controls Statements :-
# Conditional Statements or Selection Statements :-
# if
# if-else
# if-elif-else
# if-elif
# Iterative Statements (Loops) :-
# for
# while
# Transfer Staements :-
# break
# continue
# pass
# del
# 1. Conditional Statements :-¶
In [11]:
# 1. if :-
In [13]:
# if condition:
# body
# Indentation is important in Python
In [5]:
# if condition:
# statement
# statement
# statement
# statements
# statements
In [7]:
name = input('Enter Your Name:')
if name == 'durga':
print('Hello Durga!')
print('How are you')
Hello Durga! How are you
In [10]:
# 2. if-else :-
In [14]:
# if condition:
# action-1
# else:
# action-2
In [16]:
name = input('Enter Your Name:')
if name == 'durga':
print('Hello Durga!')
else:
print('Hello Guest!')
print('How are you')
Hello Guest! How are you
In [21]:
# 3. if-elif-else :-
In [22]:
# if condition-1:
# action-1
# elif condition-2:
# action-2
# elif condition-3:
# action-3
# elif condition-4:
# action-4
# ....
# else:
# default Action
In [23]:
brand = input('Enter Your Favourite Brand:')
if brand == 'RC':
print('RC is a great brand')
elif brand == 'KF':
print('KF is a great brand')
elif brand == 'KO':
print('KO is a great brand')
elif brand == 'FO':
print('FO is a great brand')
else:
print('I dont know that brand')
I dont know that brand
In [25]:
# 4. if-elif :-
In [27]:
# if condition-1:
# action-1
# elif condition-2:
# action-2
# elif condition-3:
# action-3
# elif condition-4:
# action-4
In [29]:
brand = input('Enter Your Favourite Brand:')
if brand == 'RC':
print('RC is a great brand')
elif brand == 'KF':
print('KF is a great brand')
elif brand == 'KO':
print('KO is a great brand')
elif brand == 'FO':
print('FO is a great brand')
print('I don\'t know brand')
I don't know brand
In [30]:
n1 = int(input('Enter First Number: '))
n2 = int(input('Enter Second Number: '))
if n1 > n2:
print(f'{n1} is greater than {n2}')
else:
print(f'{n1} is smaller than {n2}')
545 is greater than 54
In [ ]:
# 2. Iterative Statements :-¶
In [2]:
# for loop
# while loop
In [3]:
# 1. for loop :-
# for every element present in the given sequence, if we want to perform certain activity then we should go for for loop.
# for x in sequence:
# body
In [4]:
l = [10,20,30,40,50,60]
s = {10,20,30,40,50,60}
In [5]:
for x in l:
print(x)
10 20 30 40 50 60
In [10]:
x = 'durga'
for ch in x:
print('The Current Character is:',ch)
The Current Character is: d The Current Character is: u The Current Character is: r The Current Character is: g The Current Character is: a
In [12]:
s = input('Enter Any String:')
i = 0
for ch in s:
print('The Character Present at', i, 'index:', ch)
i += 1
The Character Present at 0 index: 3 The Character Present at 1 index: 4 The Character Present at 2 index: k The Character Present at 3 index: j The Character Present at 4 index: b The Character Present at 5 index: g
In [13]:
for x in range(10):
print('Hello')
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
In [14]:
for x in range(10):
print(x)
0 1 2 3 4 5 6 7 8 9
In [17]:
for x in range(1, 21):
if x%2 == 0:
print(x)
2 4 6 8 10 12 14 16 18 20
In [20]:
for x in range(10, 0, -1):
print(x)
10 9 8 7 6 5 4 3 2 1
In [ ]:
In [1]:
# To print the sum of numbers present in the given list?
In [4]:
l = eval(input('Enter List:'))
print(l)
sum = 0
for x in l:
sum += x
print('Sum is:', sum)
(10, 10, 20, 30, 40, 50) Sum is: 160
In [6]:
# while loop :-
# We don't know the number of iteration in advance, as long as some condition is True, execute body
# while condition:
# True
In [11]:
# To print numbers from 1 to 10 by using while loop?
In [12]:
x = 1
while x <= 10:
print(x)
x += 1
1 2 3 4 5 6 7 8 9 10
In [13]:
# # Note :-
# for loop is sequence based
# while loop is condition based
In [14]:
# To display the sum of first n natural numbers?
In [16]:
n = int(input('Enter n values:'))
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print('The sum of First {} Numbers: {}'.format(n, sum))
The sum of First 9 numbers: 45
In [17]:
name = ''
i = 1
while name != 'sunny' and i<=10:
name = input('Enter Name:')
print('Enter Name:', name)
i += 1
Enter Name: 454 Enter Name: SADA Enter Name: ASDSLAMF Enter Name: DSFKLER Enter Name: KVNFA Enter Name: KNAFSKASF Enter Name: FAKSNFK Enter Name: MLSNFL Enter Name: MCKEANF Enter Name: sunny
In [18]:
name = ''
i = 1
while name != 'sunny' and i<=10:
name = input('Enter Name:')
print('Enter Name:', name)
i += 1
if i == 10:
print('You entered more than 10 times. Exiting...')
break
print('Thanks for Confirmation')
Enter Name: sfew Enter Name: wgrw Enter Name: eg Enter Name: erwg Enter Name: wrgrw Enter Name: g Enter Name: gtrt Enter Name: wgw Enter Name: rg You entered more than 10 times. Exiting... Thanks for Confirmation
In [19]:
# name != 'sunny' and i<=10 ===> Returns False then only it will be stopped
# name != 'sunny' ===> If you enter name as sunny the the result is False
# i<=10 ===> If i value > 10 then it results False
In [20]:
# Infinite Loop :-
# Nested Loop :-
# Loop inside another loop
In [21]:
for i in range(4):
for j in range(4):
print(i, j)
0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 2 3 3 0 3 1 3 2 3 3
In [22]:
# read data from the end user as long as he poviding valing input
# while data is invalid:
# read data from the user
# while True:
# read data from the user
# if data is valid:
# break
In [25]:
while True:
username = input('Enter User Name:')
pwd = input('Enter Password:')
if username == 'durga' and pwd == 'sunny':
print('Login Successful')
break
else:
print('Invalid Credentials. Please try again.')
Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Login Successful
In [ ]:
In [4]:
n = int(input('Enter any Number:'))
for i in range(n):
print('*', end=' ')
* * * * *
In [7]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(n):
print('*', end=' ')
print()
* * * * * * * * *
In [10]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(n):
print(n, end=' ')
print()
3 3 3 3 3 3 3 3 3
In [12]:
n = int(input('Enter any Number:'))
for i in range(n):
print('A '*n)
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
In [18]:
n = int(input('Enter any Number:'))
for i in range(n):
print((str(i+1) + ' ')* n)
1 1 2 2
In [22]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row
for j in range(n): # for every column in that row
print(i+1, end=' ')
print()
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
In [21]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row
for j in range(n): # for every column in that row
print(i, end=' ')
print()
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4
In [25]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row
for j in range(n): # for every column in that row
print(chr(65+i), end=' ')
print()
A A A A A A A A A B B B B B B B B B C C C C C C C C C D D D D D D D D D E E E E E E E E E F F F F F F F F F G G G G G G G G G H H H H H H H H H I I I I I I I I I
In [ ]:
In [1]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row i = 1,2,3,4,....,n
for j in range(n): # j = 1,2,3,4,..,n
print(j+1, end=' ')
print()
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
In [4]:
n = int(input('Enter any Number:'))
for i in range(1, n+1): # for every row i = 1,2,3,4,....,n
for j in range(1, n+1): # j = 1,2,3,4,..,n
print(j+1, end=' ')
print()
2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6
In [5]:
n = int(input('Enter any Number:'))
for i in range(1, n+1): # for every row i = 1,2,3,4,....,n
for j in range(1, n+1): # j = 1,2,3,4,..,n
print(j, end=' ')
print()
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
In [13]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row i = 1,2,3,4,....,n
for j in range(n): # j = 1,2,3,4,..,n
print(n-j, end=' ')
print()
5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1
In [16]:
for i in range(10, 1, -1):
print(i)
10 9 8 7 6 5 4 3 2
In [26]:
n = int(input('Enter any Number:'))
for i in range(n):
print('*' * (i+1))
* ** ***
In [30]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(i+1):
print('*', end=' ')
print()
* * * * * *
In [41]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(i+1):
print(n-j, end=' ')
print()
5 5 4 5 4 3 5 4 3 2 5 4 3 2 1
In [57]:
n = int(input('Enter any Number:'))
for i in range(n):
print(' '*(n-i-1), end='')
print('* '*(i+1))
* * * * * * * * * * * * * * *
In [ ]:
# Transfer Statements :-¶
In [1]:
# 1. break
# 2. continue
# pass and del
# 1. break statement :-¶
In [24]:
# break loop execution based on some condition
In [4]:
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
In [6]:
for i in range(10):
print(i)
if i == 5:
print('Loop Execution enough... plz break!!')
break;
0 1 2 3 4 5 Loop Execution enough... plz break!!
In [8]:
cart = [10,20,30,40,600,50,60]
for items in cart:
if items > 500:
print('To place this order, insurance must be required')
break
print(items)
10 20 30 40 To place this order, insurance must be required
# 2. continue statement :-¶
In [ ]:
# we can use continue statement to skip current iteration and continue for the next iteration.
In [12]:
for i in range(10):
if i == 5:
continue
print(i)
0 1 2 3 4 6 7 8 9
In [14]:
for i in range(10):
if i%2 == 0:
continue
print(i)
1 3 5 7 9
In [15]:
for i in range(10):
if i%2 != 0:
continue
print(i)
0 2 4 6 8
In [16]:
cart = [10,20,30,40,600,500,60]
for item in cart:
if item >= 500:
print('We cannot process this item beacuse of insurance issue:', item)
continue
print('Processing item:', item)
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 We cannot process this item beacuse of insurance issue: 600 We cannot process this item beacuse of insurance issue: 500 Processing item: 60
In [19]:
numbers = [10,20,0,5,0,30]
for n in numbers:
if n == 0:
print('We cannot divide with 0')
continue
print('100/{} = {}'.format(n, 100/n))
100/10 = 10.0 100/20 = 5.0 We cannot divide with 0 100/5 = 20.0 We cannot divide with 0 100/30 = 3.3333333333333335
In [20]:
numbers = [10,20,0,5,0,30]
for n in numbers:
if n == 0:
print('We cannot divide with 0')
continue
print('100/{a} = {b}'.format(a=n, b=100/n))
100/10 = 10.0 100/20 = 5.0 We cannot divide with 0 100/5 = 20.0 We cannot divide with 0 100/30 = 3.3333333333333335
In [22]:
# if-else
# for-else
# while-else
# try-else-except-finally
# else block :-¶
In [35]:
# loops with else block :-
# 1. some times loop will be executed with out break
# 2. some times loop will be terminated because of break
# inside loop execution if break statement not executed, then only else part will be executed
# else means loop without break
# else is always associated with break
# without break we can use else but not that much meaningful.
In [27]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 Processing item: 50
In [28]:
cart = [10,20,30,40,500]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 we cannot place this order
In [29]:
cart = [10,20,30,40,500]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 we cannot place this order
In [30]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 Processing item: 50 Congrats!
In [33]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
continue
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 Processing item: 50 Congrats!
In [34]:
cart = [10,20,30,40,500]
for item in cart:
if item > 50:
print('we cannot place this order')
continue
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 we cannot place this order Congrats!
In [37]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
for i in range(2):
if i == 1:
break
print(i)
else:
print('Congrats!')
Processing item: 10 0 Processing item: 20 0 Processing item: 30 0 Processing item: 40 0 Processing item: 50 0 Congrats!
In [ ]:
In [1]:
# 1. Selection Statements/Conditional Statements :-
# if
# if-else
# if-elif
# if-elif-else
# 2. Iteration Statements (Loops) :-
# for
# while
# for-else
# while-else
# else will be executed if there is no break statement
# 3. Transfer Statements :-
# break
# continue
# # pass and del :-¶
# pass :-¶
In [12]:
# it is a keyword in python
# it is empty statement
# it is null statement
# it won't do anything
In [10]:
if 10>20:
print('Hello')
else:
Cell In[10], line 3 else: ^ SyntaxError: incomplete input
In [7]:
if 10>20:
print('Hello')
else:
pass
In [1]:
class Loan:
pass
In [2]:
class GoldLoan(Loan):
pass
In [3]:
class HomeLoan(Loan):
pass
In [4]:
class CarLoan(Loan):
pass
In [5]:
class Loan:
def getInterestRate(self):
pass
In [6]:
class GoldLoan(Loan):
def getInterestRate(self):
return 10
In [8]:
class HomeLoan(Loan):
def getInterestRate(self):
return 7
In [9]:
class CarLoan(Loan):
def getInterestRate(self):
return 13
# del :-¶
In [11]:
s1 = 'durga'
print(s1)
durga
In [12]:
s1 = 'durga'
del s1
print(s1)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[12], line 3 1 s1 = 'durga' 2 del s1 ----> 3 print(s1) NameError: name 's1' is not defined
In [13]:
s1 = 'durga'
s1 = None
print(s1)
None
In [16]:
s1 = 'durga'
print(s1)
print(s1[0])
durga d
In [18]:
del s1[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[18], line 1 ----> 1 del s1[0] TypeError: 'str' object doesn't support item deletion
In [20]:
# pass ===> empty statement
# del ===> to delete variable which are no longer required in our progream automatically the corresponding objects for gc.
# if useless objects deleted, free memory will be improved our program won't face memory issues.
In [21]:
del 'durga'
Cell In[21], line 1 del 'durga' ^ SyntaxError: cannot delete literal
In [22]:
s = 'durga'
del s
In [ ]:
# # String Data Types :-¶
In [2]:
s = 'durga'
s = 'ravi'
In [3]:
# either single quotes or double quotes
In [4]:
ch = 'a'
In [5]:
s = '''durga
software
solutions'''
print(s)
durga software solutions
In [6]:
# 1. To define multiline string literals.
# 2. To use single o rdouble quotes as symbol only.
# 3. Doc string.
In [9]:
s = '''The classes of 'Python' by "Durga Sir" are good'''
print(s)
The classes of 'Python' by "Durga Sir" are good
In [10]:
s = 'The classes of \'Python\' by \"Durga Sir\" are good'
print(s)
The classes of 'Python' by "Durga Sir" are good
In [12]:
# How to access character of the string :-
# 1. By using index
# 2. By using Slice Operator
# 1. By using index :-¶
In [17]:
# Python supports both +ve and -ve indices :-
# +ve index is always from left to right starts from 0.
# -ve index is always from right to left starts from -1.
In [19]:
s = 'durga'
print(s)
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
durga d u r g a
In [20]:
print(s[5])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[20], line 1 ----> 1 print(s[5]) IndexError: string index out of range
In [21]:
s = 'durga'
print(s)
print(s[-1])
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
durga a g r u d
In [22]:
print(s[-6])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[22], line 1 ----> 1 print(s[-6]) IndexError: string index out of range
In [24]:
# Question :-
# Write a program to read string from the keyboard and display its characters by index wise(both positive index and negative index)?
In [32]:
s = input('Enter String:')
i = 0
for x in s:
print('The Character Present at', i, 'index:', x)
i += 1
# Not correct
j = -len(s)
print(j)
for x in s[::-1]:
print('The Character Present at', j, 'index:', x)
j += 1
The Character Present at 0 index: a The Character Present at 1 index: s The Character Present at 2 index: d -3 The Character Present at -3 index: d The Character Present at -2 index: s The Character Present at -1 index: a
In [33]:
s = input('Enter any String:')
i = 0
for x in s:
print('The Character Present at Positive Index {} and at Negative Index {} is : {}'. format(i, i-len(s), x))
i += 1
The Character Present at Positive Index 0 and at Negative Index -3 is : a The Character Present at Positive Index 1 and at Negative Index -2 is : s The Character Present at Positive Index 2 and at Negative Index -1 is : d
# 2. By using Slice Operator :-¶
In [51]:
# s[begin_index:end_index:step]
# s[begin:end:step]
# s[begin_index:end_index]
# from begin_index to end_index
# begin is optional
In [36]:
s = 'Learning Python is very Easy'
In [46]:
s[:]
Out[46]:
'Learning Python is very Easy'
In [45]:
s[:7]
Out[45]:
'Learnin'
In [44]:
s[1:7]
Out[44]:
'earnin'
In [43]:
s[1:7:1]
Out[43]:
'earnin'
In [42]:
s[1:7:2]
Out[42]:
'eri'
In [47]:
s = 'abcdefghijklmnopqrstuvwxyz'
In [49]:
s[1:15:1]
Out[49]:
'bcdefghijklmno'
In [50]:
s[1:15:3]
Out[50]:
'behkn'
In [52]:
# for begin and end we can take either positive index or negative index
In [53]:
s[1:10000:1]
Out[53]:
'bcdefghijklmnopqrstuvwxyz'
In [54]:
# Slice Operator won't raise index error
In [55]:
s[11100:1000:1]
Out[55]:
''
In [56]:
s[-5:-9:-1]
Out[56]:
'vuts'
In [58]:
# steps value can be either positive or negative.
# The default step value is: +1.
# +ve step value means forward direction(left to right)
# from begin to end-1 index
# -ve step value means backward direction(right to left)
# from end to begin-1 index
In [59]:
s[::1]
Out[59]:
'abcdefghijklmnopqrstuvwxyz'
In [60]:
s[::-1]
Out[60]:
'zyxwvutsrqponmlkjihgfedcba'
In [61]:
# In Forward Direction:
# default begin value: 0
# default end value: len(s)
# default step value: +1
# In Backward Direction:
# default begin value: -1
# default end value: -len(s)+1
# default step value: -1
In [62]:
s
Out[62]:
'abcdefghijklmnopqrstuvwxyz'
In [63]:
s[::-1]
Out[63]:
'zyxwvutsrqponmlkjihgfedcba'
In [64]:
len(s)
Out[64]:
26
In [65]:
s[-1:-27:-1]
Out[65]:
'zyxwvutsrqponmlkjihgfedcba'
In [66]:
# In Forward direction if end value is 0 then result is always empty.
# In Backward direction if end value is -1 then result is always empty.
In [68]:
# s[begin:end:step]
# all attributes are optional
# all values can be either positive or negative
# if step is +ve then forward direction from begin to end-1
# if step is -ve then backward direction from begin to end+1
In [ ]:
In [1]:
s = 'abcdefghij'
In [2]:
s[1:6:2]
Out[2]:
'bdf'
In [3]:
s[3:7:-1]
Out[3]:
''
In [5]:
s[7:4:-1]
Out[5]:
'hgf'
In [6]:
s[0:10000:1]
Out[6]:
'abcdefghij'
In [7]:
s[1:10000:-1]
Out[7]:
''
In [8]:
s[-4:1:-1]
Out[8]:
'gfedc'
In [9]:
s[-4:1:-2]
Out[9]:
'gec'
In [10]:
s[5:0:1]
Out[10]:
''
In [11]:
s[9:0:0]
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[11], line 1 ----> 1 s[9:0:0] ValueError: slice step cannot be zero
In [12]:
s[0:-10:-1]
Out[12]:
''
In [13]:
s[-1:-1:-1]
Out[13]:
''
In [14]:
s[0:-2:1]
Out[14]:
'abcdefgh'
In [15]:
s[1:7:3]
Out[15]:
'be'
In [17]:
s[7:1:-3]
Out[17]:
'he'
In [20]:
s = input('Enter any string')
print('In Forward direction')
i= 0
while i< len(s):
print(s[i])
i+=1
print('In Backward direction')
i = -1
while i > -len(s)-1:
print(s[i])
i -= 1
In Forward direction 4 5 6 In Backward direction 6 5 4
In [21]:
# Membership Operator :-
# in
# not in
In [22]:
s = 'durga'
In [23]:
'a' in s
Out[23]:
True
In [24]:
'b' in s
Out[24]:
False
In [25]:
'b' not in s
Out[25]:
True
In [ ]:
In [29]:
# Number to Word Conversion :-
s = int(input('Enter the number:'))
s = s%26
num = 65 + s
word = chr(num)
print(word)
M
# Comparison of Strings :-¶
In [32]:
# >, >=, <=, <, ==
In [33]:
s1 = input('Enter First String:')
s2 = input('Enter Second String:')
if s1 == s2:
print('Both Strings are equal.')
elif s1 > s2:
print('First String is greater than Second String.')
else:
print('First String is smaller than Second String.')
Both Strings are equal.
In [36]:
city = input('Enter City:')
if city == 'Hyderabad':
print('Hello Hyderabadi...Aadaab')
elif city == 'Chennai':
print('Hello Madrasi...Vanakkam')
elif city == 'Bangalore':
print('Hello Kannadiga...Namaskaran')
else:
print('I am not familiar with', city)
I am not familiar with 456
# Remove Spaces From the Strings :-¶
In [37]:
# # Remove Spaces From the Strings :-
# rstrip ---> To remove spaces at right hand side(end of the string)
# lstrip ---> To remove spaces from left hand side(beginning of the string)
# strip ---> To remove both sides
# but it will not work on spaces b/w the words
# ex. it will not work on 'Hydera bad'
In [38]:
city = input('Enter City:').strip()
if city == 'Hyderabad':
print('Hello Hyderabadi...Aadaab')
elif city == 'Chennai':
print('Hello Madrasi...Vanakkam')
elif city == 'Bangalore':
print('Hello Kannadiga...Namaskaran')
else:
print('I am not familiar with', city)
Hello Hyderabadi...Aadaab
In [40]:
city = input('Enter City:').strip().lower()
if city == 'hyderabad':
print('Hello Hyderabadi...Aadaab')
elif city == 'chennai':
print('Hello Madrasi...Vanakkam')
elif city == 'bangalore':
print('Hello Kannadiga...Namaskaran')
else:
print('I am not familiar with', city)
I am not familiar with ghdshas
# Finding Substrings :-¶
In [42]:
# # Finding Substrings :-
# find()
# index()
# rfind()
# rindex()
In [55]:
# string.find(substring)
# Returns index of first occurrence of the given substring
# Returns -1 if it is not available
# find() will search complete string until finding the first occurrence in forward direction
In [56]:
s = 'Learning Python is very Python easy study Python'
s.find('Python')
Out[56]:
9
In [57]:
s.find('Java')
Out[57]:
-1
In [58]:
# Membership Operator :- (in and not in)
# provide True and False
# in ===> True
In [59]:
s.find('r')
Out[59]:
3
In [60]:
s.rfind('Python')
Out[60]:
42
In [64]:
# find(substring)
# find(substring, begin, end)
# from begin to end-1
In [65]:
s.find('Python', 1, 6)
Out[65]:
-1
In [66]:
s.find('Python', 1, 26)
Out[66]:
9
In [ ]:
In [1]:
s = 'Learning python is very easy'
In [2]:
s.find('p')
Out[2]:
9
In [3]:
len(s)
Out[3]:
28
In [4]:
s = 'abc'
len(s)
Out[4]:
3
In [6]:
s = 'Learning python is very easy'
s.rfind('y')
Out[6]:
27
In [16]:
# index() :-
# index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError.
In [11]:
s.find('p')
Out[11]:
9
In [12]:
s.index('p')
Out[12]:
9
In [13]:
s.find('pt')
Out[13]:
-1
In [14]:
s.index('pt')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[14], line 1 ----> 1 s.index('pt') ValueError: substring not found
In [17]:
# Program to display all positions of the substring in the given main string?
In [24]:
s = input('Enter the String:')
subs = input('Character to Find in String:')
print('String:', s)
print('Character:', subs)
count = 0
for i in s:
if i == subs:
count += 1
print(count)
String asafasdf Character a 3
In [30]:
s = input('Enter Main String:')
subs = input('Enter Sub String:')
print('Main String:', s)
print('Sub String:', subs)
n = len(s)
pos = 0
count = 0
while True:
i = s.find(subs, pos, n)
if i == -1:
print('The Total Number of Times Sub String Found:', count)
break
else:
print('Found at index:', i)
count += 1
pos = i + len(subs)
i = s.find(subs, pos, n)
Main String: asdfghjkasdfasdfgasasas Sub String: a Found at index: 0 Found at index: 8 Found at index: 12 Found at index: 17 Found at index: 19 Found at index: 21 The Total Number of Times Sub String Found: 6
# Counting Sub-String in the Given String :-¶
In [33]:
# count() method
# s.count(substring)
# s.count(substring, begin, end)
In [35]:
s = input('Enter Main String:')
subs = input('Enter Sub String:')
print('The Total Number of Times Sub String Found:', s.count(subs))
print('The Total Number of Times Sub String Found:', s.count(subs, 4, 10))
The Total Number of Times Sub String Found: 5 The Total Number of Times Sub String Found: 0
# Replacing a String with Another String :-¶
In [37]:
# ab ---> xy
# s.replace('ab', 'xy')
In [38]:
s = 'Learning Python is very difficult'
In [39]:
s1 = s.replace('difficult', 'easy')
s1
Out[39]:
'Learning Python is very easy'
In [40]:
# Write a script to remove spaces in the given string?
# strip() ---> begining and end of the string but not middle blank spaces
In [41]:
s = 'ab a b aba b a bab'
s1 = s.replace(' ', '')
s1
Out[41]:
'abababababab'
In [43]:
s = 'ab a b aba b a bab'
s1 = s.replace(' ', '')
print(len(s)-len(s1))
6
In [45]:
s = 'ab a b aba b a bab'
s
Out[45]:
'ab a b aba b a bab'
In [46]:
s1 = s.replace(' ', '')
s1
Out[46]:
'abababababab'
In [48]:
s
Out[48]:
'ab a b aba b a bab'
# Splitting of Strings :-¶
In [54]:
# s.split(separator)
In [50]:
s = 'durga software solutions'
s
Out[50]:
'durga software solutions'
In [52]:
l = s.split(' ')
l
Out[52]:
['durga', 'software', 'solutions']
In [53]:
for x in l:
print(x)
durga software solutions
In [55]:
s = '01-08-2020'
s
Out[55]:
'01-08-2020'
In [59]:
l = s.split('-')
l
Out[59]:
['01', '08', '2020']
In [62]:
type(l)
Out[62]:
list
In [60]:
for x in l:
print(x)
01 08 2020
In [61]:
s
Out[61]:
'01-08-2020'
In [63]:
s = 'hello'
s
Out[63]:
'hello'
In [64]:
s[0] = 'p'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[64], line 1 ----> 1 s[0] = 'p' TypeError: 'str' object does not support item assignment
In [ ]:
# Joining of Strings :-¶
In [2]:
# a group of strings(list or tuple) can be joined by using the the given delimiter.
# l = s.split(separator)
# s = separator.join(group of strings)
In [6]:
l = ['sunny', 'bunny', 'hunny']
l
Out[6]:
['sunny', 'bunny', 'hunny']
In [4]:
s = '-'.join(l)
s
Out[4]:
'sunny-bunny-hunny'
In [5]:
l
Out[5]:
['sunny', 'bunny', 'hunny']
In [9]:
t = ('10','20','30')
t
Out[9]:
('10', '20', '30')
In [10]:
s = '-'.join(t)
s
Out[10]:
'10-20-30'
In [11]:
s = ''.join(t)
s
Out[11]:
'102030'
In [12]:
s = ','.join(t)
s
Out[12]:
'10,20,30'
In [13]:
# split() ===> str to list
# join() ===> list/tuple to str
# Changing Case of a String :-¶
In [15]:
# 1. upper() ---> Every lower case character will be converted into upper case
# 2. lower() ---> Every upper case character will be converted into lower case
# 3. swapcase() ---> lower-->upper and upper-->lower
# 4. title() ---> First character of every word in upper case
# 5. capitalize ---> First word of it in uppercase remaing in lower
In [18]:
s = 'learning PYTHON is very easy'
s
Out[18]:
'learning PYTHON is very easy'
In [19]:
s.upper()
Out[19]:
'LEARNING PYTHON IS VERY EASY'
In [20]:
s.lower()
Out[20]:
'learning python is very easy'
In [21]:
s.swapcase()
Out[21]:
'LEARNING python IS VERY EASY'
In [22]:
s.title()
Out[22]:
'Learning Python Is Very Easy'
In [23]:
s.capitalize()
Out[23]:
'Learning python is very easy'
# To check Type of Characters Present in the Given String :-¶
In [25]:
# 1. isalnum() ---> a to z, A to Z, 0 to 9
# 2. isalpha() ---> a to z, A to Z
# 3. isdigit() ---> 0 to 9
# 4. islower() ---> If every alphabet is in lower case
# 5. isupper() ---> If every alphabet is in upper case
# 6. istitle() ---> If the string is in title case
# 7. isspace() ---> If the string contains only spaces
In [26]:
'Durga786'.isalnum()
Out[26]:
True
In [27]:
'durga786'.isalpha()
Out[27]:
False
In [28]:
'DurgA'.isalpha()
Out[28]:
True
In [29]:
'123456'.isdigit()
Out[29]:
True
In [30]:
'durga'.islower()
Out[30]:
True
In [31]:
'DURga'.islower()
Out[31]:
False
In [32]:
'durga1234'.islower()
Out[32]:
True
In [34]:
'ABC123'.isupper()
Out[34]:
True
In [35]:
'ABCd'.isupper()
Out[35]:
False
In [36]:
'Learning Python is very easy'.istitle()
Out[36]:
False
In [37]:
'Learning Python Is Very Easy'.istitle()
Out[37]:
True
In [38]:
' '.isspace()
Out[38]:
True
In [39]:
'a '.isspace()
Out[39]:
False
In [40]:
' a'.isspace()
Out[40]:
False
In [41]:
'Durga 123'.isalnum()
Out[41]:
False
In [43]:
'Dur ga'.isalpha()
Out[43]:
False
In [46]:
s = input('Enter ANY Character:')
print(s)
if s.isalnum():
print('The Character is Alphanumeric.')
if s.isalpha():
print('The Character is Alphabet.')
if s.islower():
print('The Character is Lowercase.')
else:
print('The Character is Uppercase.')
elif s.isdigit():
print('It is a digit.')
else:
print('It is a Mixed String.')
elif s.isspace():
print('It is Space Character.')
else:
print('Non Space Special Character.')
23125safsda The Character is Alphanumeric. It is a Mixed String.
# Checking Starting and Ending Part of the String :-¶
In [48]:
# s.startswith(substring)
# s.endswith(substring)
In [50]:
s = 'learning python is very easy'
s
Out[50]:
'learning python is very easy'
In [51]:
s.startswith('l')
Out[51]:
True
In [52]:
s.startswith('learning python')
Out[52]:
True
In [53]:
s.endswith('learning python')
Out[53]:
False
In [54]:
s.endswith('sy')
Out[54]:
True
In [55]:
s.endswith('very easy')
Out[55]:
True
In [ ]:
In [1]:
# # Important programs regarding string concept?
In [53]:
# Q1: Write a program to reverse the given string?
In [6]:
str = input('Enter any String:')
print('String:', str)
reverse_str = ''
for i in str[::-1]:
reverse_str = reverse_str + i
print('Reversed String:', reverse_str)
String: asd Reversed String: dsa
In [12]:
str = input('Enter any String:')
print('String:', str)
r = reversed(str)
print(type(r))
print(r)
output = ''.join(r)
print('Reversed String:', output)
String: asdg <class 'reversed'> <reversed object at 0x00000106A384AA10> Reversed String: gdsa
In [13]:
str = input('Enter any String:')
print('String:', str)
i = len(str) - 1
target = ''
while i >= 0:
target += str[i]
i -= 1
print('Reversed String:', target)
String: asd Reversed String: dsa
In [14]:
# Q2: Program to reverse order of words?
In [21]:
str = input('Enter any String:')
print('String:', str)
l = str.split()
print(l)
l1 = []
i = len(l)-1
while i >= 0:
print(l[i])
l1.append(l[i])
i -= 1
print('Reversed List:', l1)
print('Reversed Order of Words:', ' '.join(l1))
String: asad cdv vdfb ['asad', 'cdv', 'vdfb'] vdfb cdv asad Reversed String: ['vdfb', 'cdv', 'asad'] Reversed Order of Words: vdfb cdv asad
In [25]:
str = input('Enter any String:')
print('String:', str)
l = str.split()
print(l)
for i in range(len(l)):
print(l[i])
String: as cd vf ['as', 'cd', 'vf'] as cd vf
In [26]:
str = input('Enter any String:')
print('String:', str)
l = str.split()
print(l)
l1 = []
i = len(l)-1
while i >= 0:
print(l[i])
l1.append(l[i])
i -= 1
print('Reversed List:', l1)
print('Reversed Order of Words:', '-'.join(l1))
String: as df gh ['as', 'df', 'gh'] gh df as Reversed List: ['gh', 'df', 'as'] Reversed Order of Words: gh-df-as
In [28]:
# Q3: Program to reverse internal content of each word?
# input: one two three
# output: eno owt eerht
In [29]:
s = 'one two three'
print(s)
l = s.split()
print(l)
l1 = []
for x in l:
l1.append(x[::-1])
print(l1)
output = ' '.join(l1)
print(output)
one two three ['one', 'two', 'three'] ['eno', 'owt', 'eerht'] eno owt eerht
In [30]:
# Q4: Program to print cahracters at odd position and even position for the given string?
In [41]:
s = 'abcdefgh'
even = ''
odd = ''
for i in range(len(s)):
if i % 2 == 0:
even += s[i]
else:
odd += s[i]
print('Even Position Characters:', even)
print('Odd Position Characters:', odd)
Even Position Characters: aceg Odd Position Characters: bdfh
In [42]:
s = 'abcdefgh'
print('Character at even position:', s[::2])
print('Character at odd position:', s[1::2])
Character at even position: aceg Character at odd position: bdfh
In [43]:
s = 'abcdefgh'
print('Character at even Position')
i = 0
while i < len(s):
print(s[i], end=',')
i += 2
print('\nCharacter at odd Position')
i = 1
while i < len(s):
print(s[i], end=',')
i += 2
Character at even position a,c,e,g, Character at odd Position b,d,f,h,
In [44]:
s = 'abcdefgh'
even = []
odd = []
for i in range(len(s)):
if i % 2 == 0:
even.append(s[i])
else:
odd.append(s[i])
print('Even Position Characters:', even)
print('Odd Position Characters:', odd)
Even Position Characters: ['a', 'c', 'e', 'g'] Odd Position Characters: ['b', 'd', 'f', 'h']
In [46]:
# Q5: Program to merge characters of 2 strings into a single string by taking characters alternatively?
In [50]:
s1 = 'ravi'
s2 = 'teja'
output = ''
i,j = 0, 0
while i < len(s1) or j < len(s2):
output = output + s1[i] + s2[j]
i += 1
j += 1
print(output)
rtaevjia
In [51]:
s1 = 'ravikarn'
s2 = 'teja'
output = ''
i,j = 0, 0
while i < len(s1) or j < len(s2):
output = output + s1[i] + s2[j]
i += 1
j += 1
print(output)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[51], line 8 5 i,j = 0, 0 7 while i < len(s1) or j < len(s2): ----> 8 output = output + s1[i] + s2[j] 9 i += 1 10 j += 1 IndexError: string index out of range
In [52]:
s1 = 'ravikarn'
s2 = 'teja'
output = ''
i,j = 0, 0
while i < len(s1) or j < len(s2):
if i < len(s1):
output = output + s1[i]
i += 1
if j < len(s2):
output = output + s2[j]
j += 1
print(output)
rtaevjiakarn
In [ ]:
In [2]:
# Q6: Program to sort characters present in the given string. First alphabet symbols and then numeric values?
# input: B4A1D3
# output: ABD134
In [9]:
s = 'B4A1D3'
s1 = s2 = ''
for x in s:
if x.isalpha():
s1 = s1 +x
else:
s2 = s2 + x
print(s1)
print(s2)
print(sorted(s1))
print(sorted(s2))
output = ''
for x in sorted(s1):
output = output + x
for x in sorted(s2):
output = output + x
print(output)
BAD 413 ['A', 'B', 'D'] ['1', '3', '4'] ABD134
In [11]:
s = 'B4A1D3'
s1 = s2 = ''
for x in s:
if x.isalpha():
s1 = s1 +x
else:
s2 = s2 + x
print(s1)
print(s2)
print(sorted(s1))
print(sorted(s2))
output = ''.join(sorted(s1) + sorted(s2))
print(output)
BAD 413 ['A', 'B', 'D'] ['1', '3', '4'] ABD134
In [32]:
# input: a4b3c2
# output: aaaabbbcc
In [12]:
s = 'a4b3c2'
output = ''
for x in s:
if x.isalpha():
ch = x
else:
output = output + ch*int(x)
print(output)
aaaabbbcc
In [19]:
s = 'ab2cd2e2'
output = ''
ch = ''
for x in s:
if x.isalpha():
ch = ch + x
else:
output = output + ch*int(x)
ch = ''
print(output)
ababcdcdee
In [29]:
s = 'ab2cd2e2'
output = ''
num = ''
i = 0
while i < len(s):
if s[i].isalpha():
ch = s[i]
else:
num = num + s[i]
if i == len(s)-1:
output = output + ch*int(num)
if i+1 < len(s) and s[i+1].isalpha():
output = output + ch*int(num)
num = ''
i = i+1
print(output)
bbddee
In [31]:
s = 'ab10cd2e2'
output = ''
num = ''
str = ''
i = 0
while i < len(s):
if s[i].isalpha() and s[i+1].isalpha():
output = output + s[i]
elif s[i].isalpha():
ch = s[i]
else:
num = num + s[i]
if i == len(s)-1:
output = output + ch*int(num)
if i+1 < len(s) and s[i+1].isalpha():
output = output + ch*int(num)
num = ''
i = i+1
print(output)
abbbbbbbbbbcddee
In [ ]:
In [1]:
# input: a4k3b2
# output: aeknbd
In [3]:
ord('a')
Out[3]:
97
In [36]:
chr(96)
Out[36]:
'`'
In [49]:
s = 'ab24k10ba27'
output = ''
num = ''
for i in range(len(s)):
if s[i].isalpha():
ch = s[i]
output = output + ch
else:
num = num + s[i]
if i == len(s) - 1:
neword = ord(ch) + int(num)
if neword >= 123:
neword = (neword % 123) + 97
newch = chr(neword)
output = output + newch
if i+1< len(s) and s[i+1].isalpha():
neword = ord(ch) + int(num)
if neword >= 123:
neword = (neword % 123) + 97
newch = chr(neword)
output = output + newch
num = ''
print(output)
122 117 124 abzkubab
In [50]:
# Q: Program to remove duplicate characters present in the given string?
In [53]:
s = 'aaaabbbcccddd'
l = []
for i in s:
if i not in l:
l.append(i)
print(l)
''.join(l)
['a', 'b', 'c', 'd']
Out[53]:
'abcd'
In [56]:
s = input('Enter any String:')
l = []
for i in s:
if i not in l:
l.append(i)
print(l)
output = sorted(l)
output = ''.join(output)
output = output.replace(' ', '')
print(output)
['a', 's', 'd', ' ', 'm', 'e', 'j', 'v', 'f', 'n'] adefjmnsv
In [57]:
# Q: Program to find the number of occurrences of each character present in the given string?
In [59]:
d = {}
d ['a'] = 1
d['a'] = d['a']+1
print(d)
{'a': 2}
In [61]:
s = 'abcabcabbcde'
d = {}
for x in s:
if x not in d:
d[x] = 1
else:
d[x] = d[x] + 1
print(d)
for k,v in d.items():
print('{} occurs {} times'.format(k, v))
{'a': 3, 'b': 4, 'c': 3, 'd': 1, 'e': 1}
a occurs 3 times
b occurs 4 times
c occurs 3 times
d occurs 1 times
e occurs 1 times
In [ ]:
# # Collection Related DataType :-¶
In [4]:
# List
# Tuple
# Set
# Dictionary
# # List :-¶
In [3]:
# If we want to present a group of individual objects as a single entity wher insertion order preserved and duplicate objects are allowed, then we should go for list.
In [5]:
# 1. insertion order preserved
# 2. duplicate are allowed
# 3. Heterogeneous objects
# 4. It is dynamic ---> increase/decrease
# 5. mutable
# 6. indexing and slicing concepts are applicable
# 7. []
# 8. +ve and -ve index
# Creation of List Objects :-¶
In [30]:
# 1. empty list :-
In [24]:
l = []
l
Out[24]:
[]
In [31]:
# 2. if we know elements already :-
In [27]:
l = [10,20,30]
l
Out[27]:
[10, 20, 30]
In [29]:
# 3. with dynamic input :-
In [8]:
l = eval(input('enter list:'))
print(l)
print(type(l))
[10, 20, 30, 40] <class 'list'>
In [10]:
l = list(range(1,11,2))
print(l)
print(type(l))
[1, 3, 5, 7, 9] <class 'list'>
In [12]:
l = list(input('Enter String:'))
print(type(l))
print(l)
<class 'list'> ['a', 'd', 's', 's', 'a', 'f', 'd', 's']
In [18]:
# 4. list() function :-
# l = list(any other sequence)
# l = list(range(10))
In [14]:
l = list(range(1,11,3))
print(type(l))
print(l)
<class 'list'> [1, 4, 7, 10]
In [15]:
l = []
print(type(l))
print(l)
<class 'list'> []
In [16]:
l = list([10,20,30,40])
print(type(l))
print(l)
<class 'list'> [10, 20, 30, 40]
In [17]:
l = list({10,20,30,40})
print(type(l))
print(l)
<class 'list'> [40, 10, 20, 30]
In [19]:
# 5. string class split() method :-
In [21]:
s = 'Learning Python is very easy'
s
Out[21]:
'Learning Python is very easy'
In [22]:
l = s.split()
l
Out[22]:
['Learning', 'Python', 'is', 'very', 'easy']
# Accessing Elements of List :-¶
In [33]:
# by using index
# by using slice operator
In [41]:
# # by using index :-
In [35]:
l = [10,20,30,40]
l
Out[35]:
[10, 20, 30, 40]
In [36]:
l[0]
Out[36]:
10
In [37]:
l[-1]
Out[37]:
40
In [38]:
l[3]
Out[38]:
40
In [39]:
l[100]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[39], line 1 ----> 1 l[100] IndexError: list index out of range
In [40]:
# # by using slice operator :-
In [45]:
# l[begin:end:step]
# In Forward direction:
# beging to end-1
# In Backward direction:
# begin to end+1
In [44]:
l = [10,20,30,40]
l
Out[44]:
[10, 20, 30, 40]
In [46]:
l = list('abcdefghijk')
l
Out[46]:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
In [47]:
# -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
# 0 1 2 3 4 5 6 7 8 9 10
In [48]:
l[2:7:2]
Out[48]:
['c', 'e', 'g']
In [53]:
l[4::2] # from 4 to end-1 (i.e 10)
Out[53]:
['e', 'g', 'i', 'k']
In [51]:
l[8:2:-2] # from 8 to 3
Out[51]:
['i', 'g', 'e']
In [54]:
l[4:24642:2]
Out[54]:
['e', 'g', 'i', 'k']
In [56]:
# list, tuple, string ---> indexing/slicing possible
# set, dictionary ---> indexing/slicing not possible
# beacuse order is not fixed
In [64]:
# # List vs Mutability :-
In [58]:
l = [10,20,30,40]
l
Out[58]:
[10, 20, 30, 40]
In [61]:
id(l)
Out[61]:
2831139062592
In [62]:
l[0] = 777
l
Out[62]:
[777, 20, 30, 40]
In [63]:
id(l)
Out[63]:
2831139062592
# Traversing the Elements of List :-¶
In [68]:
# # Display all elements of list by using while loop :-
In [67]:
l = [10,20,30,40,50]
i = 0
while i < len(l):
print(l[i])
i += 1
10 20 30 40 50
In [69]:
l = [10,20,30,40,50]
for x in l:
print(x)
10 20 30 40 50
In [70]:
# Display only even numbers :-
In [71]:
l = [0,1,2,3,4,5,6,7,8,9,10]
for x in l:
if x % 2 == 0:
print(x)
0 2 4 6 8 10
In [72]:
# To access element on base of index use where loop
# for element base use for loop
In [74]:
l = [10,20,30,40]
i = 0
while i<len(l):
print('The element present at positive index: {} and negative index: {} is: {}'.format(i, i-len(l), l[i]))
i += 1
The element present at positive index: 0 and negative index: -4 is: 10 The element present at positive index: 1 and negative index: -3 is: 20 The element present at positive index: 2 and negative index: -2 is: 30 The element present at positive index: 3 and negative index: -1 is: 40
In [ ]:
In [9]:
# # # List Data Structure :-
# Important Functions and Methods of List :-¶
In [4]:
# functions ---> POP Concept(Procedural Oriented Programming)
# methods ---> OOP Concept(Object Oriented Programming)
In [5]:
def f1():
print('f1 function')
In [6]:
class Test:
def m1(self):
print('m1 method')
In [7]:
f1()
f1 function
In [8]:
test = Test()
test.m1()
m1 method
In [10]:
s = 'durga'
print(len(s))
print(s.upper())
5 DURGA
# 1. To get information of List :-¶
In [11]:
# 1. len() :-
# to retrun the number of elements present in the list
In [12]:
l = [10,20,30,40]
len(l)
Out[12]:
4
In [14]:
# 2. count() :-
# it returns the number of occurrences of specified element
In [15]:
l = [10,20,30,40,10,30,40,10]
l.count(10)
Out[15]:
3
In [16]:
l.count(40)
Out[16]:
2
In [17]:
l.count(50)
Out[17]:
0
In [22]:
# 3. index() :-
# it returns the index of the first occurrence of specified element
# ValueError if the element is not present in the list
# membership operator: in
In [23]:
l = [10,20,30,40,10,30,40,10]
l.index(10)
Out[23]:
0
In [24]:
l.index(40)
Out[24]:
3
In [25]:
l.index(50)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[25], line 1 ----> 1 l.index(50) ValueError: 50 is not in list
In [27]:
l = [1,2,3,1,1,1,4]
x = int(input('Enter any Element to Find Index:'))
i = l.index(x)
print('{} element first occurrence index is: {}'.format(x,i))
4 element first occurrence index is: 6
In [28]:
l = [1,2,3,1,1,1,4]
x = int(input('Enter any Element to Find Index:'))
if x in l:
i = l.index(x)
print('{} element first occurrence index is: {}'.format(x,i))
else:
print('{} element is not present in the list'.format(x))
8 element is not present in the list
# 2. Manipulating Elements of List :-¶
In [43]:
# 1. append() :-
In [41]:
l = []
l.append('A')
l.append('B')
l.append('C')
l
Out[41]:
['A', 'B', 'C']
In [42]:
l = []
for i in range(101):
if i%10 == 0:
l.append(i)
print(l)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
In [44]:
# 2. insert() :-
# To insert element ar specified index position
# If specified index is smaller than min index, then element will be inserted at beginning.
# If specified index is greater than max index, then element will be inserted at end.
In [45]:
l = [10,20,30,40,50]
l
Out[45]:
[10, 20, 30, 40, 50]
In [47]:
id(l)
Out[47]:
3050955359232
In [46]:
l.insert(1,70)
l
Out[46]:
[10, 70, 20, 30, 40, 50]
In [48]:
id(l)
Out[48]:
3050955359232
In [49]:
# l.insert(1 ,70) ---> 70 will insert at position 1
# l[1] = 70 ---> replace value at 1 with 70
In [50]:
l = [10,20,30,40,50]
l
Out[50]:
[10, 20, 30, 40, 50]
In [51]:
l.insert(-10,70)
l
Out[51]:
[70, 10, 20, 30, 40, 50]
In [52]:
l.insert(100,80)
l
Out[52]:
[70, 10, 20, 30, 40, 50, 80]
In [55]:
# # append() vs insert() :-
# append(element) ---> Element will be added in the last position
# insert(index, element) ---> Element will be added in the specified position
In [58]:
# 3. extend() :-
# l1.extend(l2)
# All elements present in l2 will be inserted to l1
In [79]:
l1 = [10,20,30,40,50]
l2 = [60,70,80]
print(l1)
print(l2)
for x in l2:
l1.append(x)
print(l1)
[10, 20, 30, 40, 50] [60, 70, 80] [10, 20, 30, 40, 50, 60, 70, 80]
In [78]:
l1 = [10,20,30,40,50]
l2 = [60,70,80]
print(l1)
print(l2)
l1.extend(l2)
print(l1)
[10, 20, 30, 40, 50] [60, 70, 80] [10, 20, 30, 40, 50, 60, 70, 80]
In [2]:
# 4. remover() :-
# remove(element)
# only first occurence
# ValueError if not present
In [12]:
l = [10,20,30,40,10,20,50]
l
Out[12]:
[10, 20, 30, 40, 10, 20, 50]
In [13]:
l.remove(10)
l
Out[13]:
[20, 30, 40, 10, 20, 50]
In [14]:
l.remove(10)
l
Out[14]:
[20, 30, 40, 20, 50]
In [15]:
l.remove(60)
l
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[15], line 1 ----> 1 l.remove(60) 2 l ValueError: list.remove(x): x not in list
In [16]:
l = [10,10,10,10,20,20,30]
x = int(input('Enter Element tot remove:'))
if x in l:
l.remove(x)
else:
print('Specified Element not avaialble')
print(l)
[10, 10, 10, 10, 20, 20]
In [18]:
l = [10,10,10,10,20,20,30]
x = int(input('Enter Element tot remove:'))
while True:
if x in l:
l.remove(x)
else:
break
print(l)
[10, 10, 10, 10, 30]
In [ ]:
In [1]:
# 5. pop() :-
# by default pop() will delete last element and returns that element.
In [2]:
l = [10,10,10,20,20,30]
print(l.pop())
print(l)
30 [10, 10, 10, 20, 20]
In [4]:
l = [10,10,10,20,20,30]
print(l.pop())
print(l.pop())
print(l.pop())
print(l)
30 20 20 [10, 10, 10]
In [5]:
l.pop()
Out[5]:
10
In [8]:
l = [10,10,10,20,20,30]
x = l.pop()
In [9]:
x
Out[9]:
30
In [16]:
l = [10,10,10]
print(l.pop())
print(l.pop())
print(l.pop())
print(l)
10 10 10 []
In [17]:
l = [10,10,10]
print(l.pop())
print(l.pop())
print(l.pop())
print(l.pop())
print(l)
10 10 10
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[17], line 6 4 print(l.pop()) 5 print(l.pop()) ----> 6 print(l.pop()) 8 print(l) IndexError: pop from empty list
In [18]:
l = [10,10,10]
print(l.pop())
print(l.pop())
print(l.pop())
if len(l) != 0:
print(l.pop())
print(l)
10 10 10 []
In [19]:
# pop() ---> last element will be deleted
# pop(index) ---> last element will be
In [28]:
l = [10,10,10,20,20,30]
print(l.pop(1))
print(l.pop(1))
print(l.pop(1))
print(l)
10 10 20 [10, 20, 30]
In [33]:
l = [10,20,30,40]
print(l)
i = 0
while i < len(l):
print(l.pop(i))
i += 1
print(l)
[10, 20, 30, 40] 10 30 [20, 40]
In [34]:
l = [10,20,30,40]
print(l)
i = 0
n = len(l)
while i < n:
print('Current index value:', i)
print('Current n value:', n)
print('The removed element:', l.pop(i))
i += 1
print(l)
[10, 20, 30, 40] Current index value: 0 Current n value: 4 The removed element: 10 Current index value: 1 Current n value: 4 The removed element: 30 Current index value: 2 Current n value: 4
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[34], line 9 7 print('Current index value:', i) 8 print('Current n value:', n) ----> 9 print('The removed element:', l.pop(i)) 11 i += 1 13 print(l) IndexError: pop index out of range
In [36]:
l = [10,20,30,40]
print(l)
while len(l) != 0:
print('The removed element:', l.pop(i))
print(l)
[10, 20, 30, 40] The removed element: 10 The removed element: 20 The removed element: 30 The removed element: 40 []
In [51]:
# # remove() vs pop() :-
# remove() :-
# element based removal
# ValueError, membership operator
# pop() :-
# index based removaland by default last element will be deleted
# IndexError
In [39]:
l = [10,20,30,40]
l
Out[39]:
[10, 20, 30, 40]
In [40]:
l.pop()
Out[40]:
40
In [41]:
l
Out[41]:
[10, 20, 30]
In [42]:
l.remove(30)
In [43]:
l
Out[43]:
[10, 20]
In [44]:
l.pop(20)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[44], line 1 ----> 1 l.pop(20) IndexError: pop index out of range
In [45]:
# pop() ---> last element will be deleted
# pop(index) ---> element will be deleted at specified index
In [ ]:
# 6. clear() :-
# to delete all elements
In [47]:
l = [10,20,30,40]
l
Out[47]:
[10, 20, 30, 40]
In [56]:
l.clear()
In [58]:
l
Out[58]:
[]
In [59]:
l = [10,20,30,40]
print(l)
print(l.clear())
print(l)
[10, 20, 30, 40] None []
In [52]:
# append()
# insert()
# extend()
# remove()
# pop()
# clear()
# Order Elements of the List :-¶
In [61]:
# 1. reverse() :-
In [62]:
l = [10,20,30,40]
print(l)
l.reverse()
print(l)
[10, 20, 30, 40] [40, 30, 20, 10]
In [64]:
# 2. sort() :-
# For numbers: Ascending order
# For strings: Alphabetic order (ASCII Based)
In [65]:
l = [10,5,15,0]
print(l)
l.sort()
print(l)
[10, 5, 15, 0] [0, 5, 10, 15]
In [66]:
l = ['sunny', 'bunny', 'vinny', 'pinny', 'chinny']
print(l)
l.sort()
print(l)
['sunny', 'bunny', 'vinny', 'pinny', 'chinny'] ['bunny', 'chinny', 'pinny', 'sunny', 'vinny']
In [67]:
l = ['sunny', 'bunny', 'vinny', 'pinny', 'chinny']
print(l)
print(l.sort())
print(l)
['sunny', 'bunny', 'vinny', 'pinny', 'chinny'] None ['bunny', 'chinny', 'pinny', 'sunny', 'vinny']
In [68]:
l = [10,5,15,0]
print(l)
print(l.sort())
print(l)
[10, 5, 15, 0] None [0, 5, 10, 15]
In [69]:
l = ['sunny', 'bunny', 10, 'pinny', 20]
print(l)
print(l.sort())
print(l)
['sunny', 'bunny', 10, 'pinny', 20]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[69], line 4 1 l = ['sunny', 'bunny', 10, 'pinny', 20] 3 print(l) ----> 4 print(l.sort()) 5 print(l) TypeError: '<' not supported between instances of 'int' and 'str'
In [70]:
l = ['sunny', 'bunny', 'vinny', 'pinny', 'chinny']
print(l)
print(l.sort(reverse=True))
print(l)
['sunny', 'bunny', 'vinny', 'pinny', 'chinny'] None ['vinny', 'sunny', 'pinny', 'chinny', 'bunny']
In [72]:
# # reverse() vs reversed() :-
# reverse() :-
# list specific method and won't return anything
# applicable only for list
# reversed() :-
# python's inbuilt function and returns reversed object
# applicable for any sequence
In [73]:
# l.sort() --->
# l.sort(reverse=True) --->
# l.sort(reverse=False) --->
# Aliasing and Cloning :-¶
In [75]:
# Aliasing :- creating duplicate reference ---> l1 = l2
# Cloning :- creating duplicate list object --->
In [82]:
# Aliasing :-
# The process of cretaing duplicate refrence variable
# l2 = l1
# Cloning :-
# The Process of creating duplicate object
# Ways to create Cloning :
# 1. By using slice operator
# 2. By using copy() method
In [83]:
# Aliasing :-
# The process of cretaing duplicate refrence variable
# l2 = l1
In [84]:
l1 = [10,20,30,40]
l2 = l1
print(l1)
print(id(l1))
print(l2)
print(id(l2))
[10, 20, 30, 40] 1435542163200 [10, 20, 30, 40] 1435542163200
In [85]:
l1[1] = 777
print(l1)
print(l2)
[10, 777, 30, 40] [10, 777, 30, 40]
In [86]:
l2[2] = 888
print(l1)
print(l2)
[10, 777, 888, 40] [10, 777, 888, 40]
In [ ]:
In [14]:
# Cloning :-
# The Process of creating duplicate object
# Ways to create Cloning :
# 1. By using slice operator
# 2. By using copy() method
In [10]:
l1 = [10,20,30,40]
l2 = l1[:]
print(l1)
print(id(l1))
print(l2)
print(id(l2))
[10, 20, 30, 40] 2546502628992 [10, 20, 30, 40] 2546502573504
In [11]:
l1[1] = 777
print(l1)
print(l2)
[10, 777, 30, 40] [10, 20, 30, 40]
In [12]:
l1 = [10,20,30,40]
l2 = l1.copy()
print(l1)
print(id(l1))
print(l2)
print(id(l2))
[10, 20, 30, 40] 2546502668224 [10, 20, 30, 40] 2546502553856
In [13]:
l1[1] = 777
print(l1)
print(l2)
[10, 777, 30, 40] [10, 20, 30, 40]
In [15]:
l1[2] = 888
print(l1)
print(l2)
[10, 777, 888, 40] [10, 20, 30, 40]
In [16]:
l2[2] = 999
print(l1)
print(l2)
[10, 777, 888, 40] [10, 20, 999, 40]
# Mathematical Operators for List Object :-¶
In [19]:
# + operator
In [20]:
a = [10,20,30]
b = [40,50,60]
c = a + b
print(c)
[10, 20, 30, 40, 50, 60]
In [21]:
a = [10,20,30]
b = [40,50,60]
c = a + 40
print(c)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[21], line 3 1 a = [10,20,30] 2 b = [40,50,60] ----> 3 c = a + 40 5 print(c) TypeError: can only concatenate list (not "int") to list
In [22]:
a = [10,20,30]
b = [40,50,60]
c = a + [40]
print(c)
[10, 20, 30, 40]
In [24]:
# + operator and extend()
# + operator :-
# both should be list
# list+list
# new object will be created and returns that object
# extend() :-
# one should be list and other can be anything
# l1.extend(l2)
# new object won't be created and to the existing object only elements will be be added
In [28]:
a = [10,20,30] + [40,50,60]
print(c)
[10, 20, 30, 40]
In [29]:
a = [10,20,30]
a.extend({'a', 'b', 'c'})
print(a)
[10, 20, 30, 'a', 'c', 'b']
In [30]:
a = [10,20,30]
b = {'a', 'b', 'c'}
c = a + b
print(c)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[30], line 4 1 a = [10,20,30] 2 b = {'a', 'b', 'c'} ----> 4 c = a + b 5 print(c) TypeError: can only concatenate list (not "set") to list
In [31]:
# * operator :-
In [32]:
x = [10,20,30]
y = x*3
print(y)
[10, 20, 30, 10, 20, 30, 10, 20, 30]
In [34]:
# equality operators(==, !=) :-
# l1 and l2
# l1 == l2 returns True
# 1. The number of elements
# 2. The order of elements
# 3. The content of the elements(including case)
In [35]:
x = ['dog', 'cat', 'rat']
y = ['dog', 'cat', 'rat']
z = ['DOG', 'CAT', 'RAT']
In [36]:
x == y
Out[36]:
True
In [37]:
x == z
Out[37]:
False
In [38]:
x != z
Out[38]:
True
In [45]:
# Comparison Operators :-
# <, >, <=, >=
# Comparison is always based on first element if first element is same then go for second element
In [46]:
x = [10,10,5]
y = [10,20,30,40,50,60]
In [47]:
x > y
Out[47]:
False
In [48]:
x >= y
Out[48]:
False
In [49]:
x < y
Out[49]:
True
In [50]:
x <= y
Out[50]:
True
In [56]:
x = ['dog', 'cat', 'rat']
y = ['dog', 'cat', 'dog']
In [57]:
x > y
Out[57]:
True
In [58]:
x >= y
Out[58]:
True
In [59]:
x < y
Out[59]:
False
In [55]:
x <= y
Out[55]:
True
In [60]:
# Membership Operators :-
# in, not in
In [61]:
x = ['dog', 'cat', 'rat']
In [62]:
'dog' in x
Out[62]:
True
In [63]:
'zebra' in x
Out[63]:
False
In [64]:
'zebra' not in x
Out[64]:
True
# Nested Lists :-¶
In [66]:
# List inside List
In [67]:
l = [10,20,[30,40]]
l
Out[67]:
[10, 20, [30, 40]]
In [68]:
l[0]
Out[68]:
10
In [69]:
l[1]
Out[69]:
20
In [70]:
l[2]
Out[70]:
[30, 40]
In [72]:
l[2][0]
Out[72]:
30
In [73]:
l[2][1]
Out[73]:
40
In [74]:
l = [10,[20,[30,[40]]]]
l
Out[74]:
[10, [20, [30, [40]]]]
In [75]:
l[1][0]
Out[75]:
20
In [77]:
l[1][1]
Out[77]:
[30, [40]]
In [78]:
l[1][1][0]
Out[78]:
30
In [79]:
l[1][1][1]
Out[79]:
[40]
In [85]:
l = [[10,20,30],[40,50,60],[70,80,90]]
print(l)
print('Elements by Row Wise:')
for x in l:
print(x)
print('Elements by Matrix Style:')
for row in l:
for element in row:
print(element, end=' ')
print()
print('Elements by Matrix Style:')
for i in range(len(l)):
for j in range(len(l[i])):
print(l[i][j], end=' ')
print()
[[10, 20, 30], [40, 50, 60], [70, 80, 90]] Elements by Row Wise: [10, 20, 30] [40, 50, 60] [70, 80, 90] Elements by Matrix Style: 10 20 30 40 50 60 70 80 90 Elements by Matrix Style: 10 20 30 40 50 60 70 80 90
# List Comprehension :-¶
In [2]:
# # List Comprehension :-
# It is very easy and compact way of creating list objects from iterable object(like list, tuple, set, dictionary, range, etc) based on some condition.
# l = [ expression for item in sequence ]
# l = [ x for x in range(15) ]
# l = [ expression for item in sequence if condition ]
# l = [ 2*item for item in range(1,11) if item%2 == 0 ]
In [88]:
range(10)
Out[88]:
range(0, 10)
In [91]:
l = [x for x in range(15)]
l
Out[91]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
In [93]:
l = [item for item in range(10)]
l
Out[93]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [94]:
l = [item*item for item in range(10)]
l
Out[94]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [95]:
l = [2*item for item in range(10)]
l
Out[95]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [96]:
l = [2*item for item in range(1,11)]
l
Out[96]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [97]:
l = [2*item for item in range(1,11) if item%2==0]
l
Out[97]:
[4, 8, 12, 16, 20]
In [100]:
l = [item*item*item for item in range(1,20) if item*item*item%2==0]
l
Out[100]:
[8, 64, 216, 512, 1000, 1728, 2744, 4096, 5832]
In [104]:
l = [int(x) for x in input('Enter Multiple Values:').split()]
l
Out[104]:
[1, 2, 54, 13, 4, 54, 31, 6, 45]
In [ ]:
In [2]:
# Create a lsit with squares of first 10 natural numbers
In [5]:
l = []
for x in range(1,11):
l.append(x*x)
print(l)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [6]:
l = [x*x for x in range(1, 11)]
print(l)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [7]:
print([x*x for x in range(1, 11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [8]:
# Create a lsit with squares of first 20 even natural numbers
In [9]:
l = []
for x in range(1, 21):
if x % 2 == 0:
l.append(x*x)
print(l)
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
In [12]:
l = [ x*x for x in range(1, 21) if x*x % 2 == 0 ]
print(l)
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
In [15]:
l = [ x**2 for x in range(1, 21) if x**2 % 2 == 0 ]
print(l)
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
In [17]:
words = ['Balaiah', 'Nag', 'Venkatesh', 'Chiranjeevi']
l = [ word[0] for word in words]
print(l)
['B', 'N', 'V', 'C']
In [20]:
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
# create a list with numbers which are present in num1 but not in num2
num3 = []
for n in num1:
if n not in num2:
num3.append(n)
print(num3)
[10, 20]
In [19]:
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
# create a list with numbers which are present in num1 but not in num2
num3 = [ x for x in num1 if x not in num2 ]
print(num3)
[10, 20]
In [21]:
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
# create a list with common numbers which are present in both lists
num3 = [ x for x in num1 if x in num2 ]
print(num3)
[30, 40]
In [22]:
s = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
words = s.split()
print(words)
['THE', 'QUICK', 'BROWN', 'FOX', 'JUMPS', 'OVER', 'THE', 'LAZY', 'DOG']
In [24]:
l = []
for word in words:
l.append([word, len(word)])
print(l)
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
In [25]:
l = [ [word, len(word)] for word in words]
print(l)
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
In [28]:
s = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
In [29]:
l = [ [word, len(word)] for word in s.split()]
print(l)
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
In [30]:
l = [ [word.lower(), len(word)] for word in s.split()]
print(l)
[['the', 3], ['quick', 5], ['brown', 5], ['fox', 3], ['jumps', 5], ['over', 4], ['the', 3], ['lazy', 4], ['dog', 3]]
In [31]:
l = [ [word.capitalize(), len(word)] for word in s.split()]
print(l)
[['The', 3], ['Quick', 5], ['Brown', 5], ['Fox', 3], ['Jumps', 5], ['Over', 4], ['The', 3], ['Lazy', 4], ['Dog', 3]]
In [32]:
l = [ [word.title(), len(word)] for word in s.split()]
print(l)
[['The', 3], ['Quick', 5], ['Brown', 5], ['Fox', 3], ['Jumps', 5], ['Over', 4], ['The', 3], ['Lazy', 4], ['Dog', 3]]
In [33]:
# Program to display unique vowels present in the given word?
# Example-> 'DURGA'
In [34]:
word = input('Enter any word to Search for vowels:')
print(word)
vowels = ['a', 'e', 'i', 'o', 'u']
found = []
for v in vowels:
if v in word:
found.append(v)
print('Unique Vowels Present:', found)
adasfasdfaadsa Unique Vowels Present: ['a']
In [36]:
word = input('Enter any word to Search for vowels:')
print(word)
found = [ v for v in vowels if v in word]
print('Unique Vowels Present:', found)
aeiojaksdkbvadksfa Unique Vowels Present: ['a', 'e', 'i', 'o']
In [42]:
l =[1,2,3]
In [43]:
l.extend(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[43], line 1 ----> 1 l.extend(10) TypeError: 'int' object is not iterable
In [44]:
l.extend('durga')
print(l)
[1, 2, 3, 'd', 'u', 'r', 'g', 'a']
In [ ]:
# # Tuple Data Structure :-¶
In [16]:
# 1. It is exactly same as list exvcept thta it is immutable.
# Once we creates tuple object, we cannot change its content.
# It is read only version of list.
# 2. Duplicates are allowed
# 3. Order will be preserved
# 4. index and slicing concepts are applicable
# 5. heterogeneous objects area allowed
# 6. ()
# 7. parenthesis are optional
# single valued tuple ===> , is manadatory
In [3]:
l = [10, 20, 30, 40]
print(l)
l[0] = 777
print(l)
[10, 20, 30, 40] [777, 20, 30, 40]
In [4]:
t = (10, 20, 30, 40)
print(t)
(10, 20, 30, 40)
In [5]:
t[0] = 777
print(t)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[5], line 1 ----> 1 t[0] = 777 2 print(t) TypeError: 'tuple' object does not support item assignment
In [ ]:
In [6]:
t = (10, 20, 10, 'durga', '40')
t
Out[6]:
(10, 20, 10, 'durga', '40')
In [7]:
t[0]
Out[7]:
10
In [8]:
t[1:4]
Out[8]:
(20, 10, 'durga')
In [13]:
t = 10,20,30,40
type(t)
Out[13]:
tuple
In [12]:
t = 10,
type(t)
Out[12]:
tuple
In [14]:
t = (10)
type(t)
Out[14]:
int
In [15]:
t = (10,)
type(t)
Out[15]:
tuple
In [17]:
t = ()
type(t)
Out[17]:
tuple
In [ ]:
In [2]:
# list is mutable where as tuple is immutable
# facebook/ youtube comments section ---> List
# vendor machines ---> The allowed inputs are always fixed ---> tuple
# Bank Application
# account_types: Savings, Current ---> tuple
# Deposit machines..... like Notes are fixed(100, 200, 500, 2000)
In [4]:
# list ---> to access element l[10] ---> 10ns
# tuple ---> to access element t[10] ---> 6ns
# 100 elements ---> list ---> 100Bytes
# 100 elements ---> tuple ---> 60Bytes
In [9]:
import sys
l = [10, 20, 30, 40, 50, 60, 70, 80, 90]
t = (10, 20, 30, 40, 50, 60, 70, 80, 90)
print(sys.getsizeof(l))
print(sys.getsizeof(t))
136 112
In [5]:
# A sequence of elements
# order is important
# duplicates are allowed
In [6]:
# # Tuple Creation :-
In [7]:
t = ()
type(t)
Out[7]:
tuple
In [8]:
# list ---> tuple
# set ---> tuple
# By Using tuple() Function :-¶
In [12]:
l = [10, 20, 30]
print(l)
t = tuple(l)
print(t)
[10, 20, 30] (10, 20, 30)
In [13]:
r = range(10)
t = tuple(r)
print(t)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
In [16]:
# eval() :-
In [14]:
t = eval(input('Enter tuple Value:'))
print(type(t))
print(t)
<class 'tuple'> (4164564, 121, 54)
In [15]:
l = eval(input('Enter List Value:'))
print(type(l))
print(l)
<class 'tuple'> (54, 5415, 5465, 415)
In [17]:
# # Accessing Elements of Tuple :-
In [21]:
# by using index
# by using slice opeartor
In [22]:
t = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
t
Out[22]:
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
In [23]:
t[0]
Out[23]:
10
In [24]:
t[5]
Out[24]:
60
In [25]:
t[1:8:2]
Out[25]:
(20, 40, 60, 80)
# Tuple vs Immutable :-¶
In [27]:
# Tuples are immutable
In [28]:
t = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
t
Out[28]:
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
In [29]:
t[0] = 777
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[29], line 1 ----> 1 t[0] = 777 TypeError: 'tuple' object does not support item assignment
# Mathematical Operators :-¶
In [67]:
# +, *, ==, !=, >, >=, <, <=
In [58]:
t1 = (10, 20, 30)
t2 = (40, 50, 60)
print(t1)
print(t2)
(10, 20, 30) (40, 50, 60)
In [59]:
t3 = t1 + t2
print(t3)
(10, 20, 30, 40, 50, 60)
In [60]:
t4 = t1 * 3
print(t4)
(10, 20, 30, 10, 20, 30, 10, 20, 30)
# Important Functions and method related to Tuple :-¶
In [61]:
# 1. len()
# 2. count()
# 3. index()
# 4. sorted()
# 5. min()
# 6. max()
In [62]:
t = (10, 20, 30)
len(t)
Out[62]:
3
In [63]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.count(10)
Out[63]:
3
In [64]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.index(10)
Out[64]:
0
In [65]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.index(40)
Out[65]:
3
In [66]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.index(52)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[66], line 2 1 t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10) ----> 2 t1.index(52) ValueError: tuple.index(x): x not in tuple
In [50]:
l = [0, 20, 5, 15, 10]
l.sort()
print(l)
[0, 5, 10, 15, 20]
In [51]:
t = (0, 20, 5, 15, 10)
t.sort()
print(t)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[51], line 2 1 t = (0, 20, 5, 15, 10) ----> 2 t.sort() 3 print(t) AttributeError: 'tuple' object has no attribute 'sort'
In [53]:
t = (0, 20, 5, 15, 10)
l1 = tuple(sorted(t))
print(l1)
(0, 5, 10, 15, 20)
In [54]:
t = (0, 20, 5, 15, 10)
l1 = tuple(sorted(t, reverse=True))
print(l1)
(20, 15, 10, 5, 0)
In [55]:
t = (0, 20, 5, 15, 10)
print(t)
print(min(t))
(0, 20, 5, 15, 10) 0
In [56]:
t = (0, 20, 5, 15, 10)
print(t)
print(max(t))
(0, 20, 5, 15, 10) 20
# sort() vs sorted() :-¶
In [72]:
# sort() is list specific method.
# Applicable only for list
# It won't create new list and in the existing list only sorting will be happening
# return type ---> None
# sorted() is general purpose python's inbuilt function.
# Applicable for any sequence
# A new lsit object will be created always
# return type ---> List
In [71]:
l = [0, 20, 5, 15, 10]
print("Before Sorting:", l)
print("Before Sorting Address:", id(l))
l.sort()
print("After Sorting:", l)
print("After Sorting Address:", id(l))
Before Sorting: [0, 20, 5, 15, 10] Before Sorting Address: 1986209712704 After Sorting: [0, 5, 10, 15, 20] After Sorting Address: 1986209712704
In [70]:
l = [0, 20, 5, 15, 10]
print("Before Sorting:", l)
print("Before Sorting Address:", id(l))
l1 = sorted(l)
print("After Sorting:", l1)
print("After Sorting Address:", id(l1))
Before Sorting: [0, 20, 5, 15, 10] Before Sorting Address: 1986209665280 After Sorting: [0, 5, 10, 15, 20] After Sorting Address: 1986209667392
In [73]:
print(l)
[0, 5, 10, 15, 20]
In [75]:
t1 = (10, 20, 30, 40)
t2 = (10, 20, 30, 40)
t3 = (20, 30, 40, 10)
print(t1)
print(t2)
print(t3)
(10, 20, 30, 40) (10, 20, 30, 40) (20, 30, 40, 10)
In [76]:
t1 == t2
Out[76]:
True
In [77]:
t1 == t3
Out[77]:
False
In [78]:
t1 != t3
Out[78]:
True
In [79]:
t1 < t2
Out[79]:
False
In [80]:
t1 < t3
Out[80]:
True
# Tuple Packing and Unpacking :-¶
In [86]:
# Tuple Packing :-
# t = a, b, c, d ===> pack 4 values into a single tuple
# Tuple Unpacking :-
# a, b, c, d = t ===> unpack 4 values from a tuple t and assign to a, b, c, d
In [83]:
a = 10
b = 20
c = 30
d = 40
t = a, b, c, d
print(t)
(10, 20, 30, 40)
In [85]:
t = (10, 20, 30, 40)
a, b, c, d = t
print(a, b, c, d)
10 20 30 40
In [87]:
t = (10, 20, 30, 40)
a, b, c, d, e = t
print(a, b, c, d, e)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[87], line 2 1 t = (10, 20, 30, 40) ----> 2 a, b, c, d, e = t 3 print(a, b, c, d, e) ValueError: not enough values to unpack (expected 5, got 4)
In [88]:
t = (10, 20, 30, 40)
a, b, c = t
print(a, b, c)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[88], line 2 1 t = (10, 20, 30, 40) ----> 2 a, b, c = t 3 print(a, b, c) ValueError: too many values to unpack (expected 3)
In [89]:
# *c ---> a group of values(tuple)
# **c ---> a group of key-value pairs(dictionary)
In [92]:
t = (10, 20, 30, 40, 50, 60, 70)
a, b, *c = t
print(a)
print(b)
print(c)
10 20 [30, 40, 50, 60, 70]
In [93]:
# *args ---> variable mumber of arguments
# **kwargs ---> variable mumber of keyword arguments
In [94]:
l = [x * x for x in range(1, 6)]
print(type(l))
print(l)
<class 'list'> [1, 4, 9, 16, 25]
In [95]:
t = (x * x for x in range(1, 6))
print(type(t))
print(t)
<class 'generator'> <generator object <genexpr> at 0x000001CE735B45F0>
# Difference b/w List and Tuple :-¶
In [101]:
# # List :-
# List is
# [10, 20, 30, 40]
# 1. Mutable
# 2. performance wise, memory wise list is not up to the mark
# 3. comprehension concept --> list
# 4. packing
# 5. List object --> non hashable/ unhashable object
# We cannot use as key in dictionary
# # Tuple :-
# Tuple is
# (10, 20, 30, 40) or 10, 20, 30, 40
# 1. Immutable
# 2. performance wise, memory wise tuple is up to the mark
# 3. comprehension concept --> not applicable
# 4. packing and unpacking
# 5. Tuple object --> hashable object
# We can use as key in dictionary
In [102]:
d = {[10, 20, 30, 40]: "durga"}
print(d)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[102], line 1 ----> 1 d = {[10, 20, 30, 40]: "durga"} 2 print(d) TypeError: unhashable type: 'list'
In [103]:
d = {(10, 20, 30, 40): "durga"}
print(d)
{(10, 20, 30, 40): 'durga'}
In [104]:
# WAP to take tuple numbers from keyboard and print ist sum and average?
In [107]:
t = eval(input("Enter Tuple Numbers:"))
print(t)
l = len(t)
sum = 0
for n in t:
sum = sum + n
print("Sum:", sum)
print('Average:',sum/l)
(1321, 63156, 43654, 63465) Sum: 171596 Average: 42899.0
In [ ]:
In [1]:
# List
# Tuple
# Order will be preserved
# Duplicates are allowed
# # Set Data Structure :-¶
In [3]:
# Order is not important
# Duplicates objects are not allowed i.e. we required to hold only unique objects.
In [4]:
# sms message.about duragasoftonline.com courses offer.
# 1 lakh mobile numbers
# duplicates are not allowed ---> we use set
In [7]:
# # Set Properties :-
# Order is not Preserved.
# indexing and slicing concepts are not applicable.
# Duplicates Objects are not allowed.
# heterogeneous objects are allowed.
# mutable and growable
# by using {} we can represent set of elements
# mathematical operations like union, intersection, difference etc.
In [9]:
s = {10, "durag", 30}
s
Out[9]:
{10, 30, 'durag'}
In [10]:
s = {10, "durag", 30, 10, 10, 20}
s
Out[10]:
{10, 20, 30, 'durag'}
# Creation of Set Objects :-¶
In [24]:
# 1. s = {10, 20, 30, 40}
# 2. s = set(any sequence)
# s = set(list)
# s = set(range)
# 3. By using eval()
In [12]:
s = {10, 20, 30, 40}
s
Out[12]:
{10, 20, 30, 40}
In [15]:
s = {20, 40, 30, 10}
s
Out[15]:
{10, 20, 30, 40}
In [16]:
l = [20, 10, 30, 10, 50, 10, 10, 40]
s = set(l)
print(s)
{40, 10, 50, 20, 30}
In [17]:
l = (20, 10, 30, 10, 50, 10, 10, 40)
s = set(l)
print(s)
{40, 10, 50, 20, 30}
In [18]:
s = set(range(10))
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
In [19]:
d = {100: "durga", 200: "ravi"}
s = set(d)
print(s)
{200, 100}
In [20]:
s = set('mississippi')
print(s)
{'s', 'i', 'p', 'm'}
In [23]:
s = eval(input('Any set of Elements:'))
print(s)
print(type(s))
{546, 3435, 46, 63463}
<class 'set'>
In [25]:
# # Empty set Objects :-
In [27]:
# s = {} ===> dict but not set
In [28]:
s = {}
type(s)
Out[28]:
dict
In [29]:
s = set()
type(s)
Out[29]:
set
# Important Methods and Functions related to Set :-¶
In [33]:
# 1. s.add(x) ---> To add an element to the set
# 2. s.update(x, y, z)
# To add multiple items to the set
# x, y, z are not individual objects, must be sequences
In [34]:
s = set()
print(s)
s.add(70)
s.add(50)
s.add(90)
s.add('ram')
s.add(50)
print(s)
set()
{50, 90, 70, 'ram'}
In [35]:
s = set()
s.update(range(1, 6))
print(s)
{1, 2, 3, 4, 5}
In [36]:
s = set()
s.update(range(1, 6), range(6, 11), "durga", "solutions")
print(s)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'r', 'd', 'n', 'l', 's', 'u', 'g', 'a', 'i', 't', 'o'}
In [39]:
s = set()
s.update(10)
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[39], line 2 1 s = set() ----> 2 s.update(10) 3 s TypeError: 'int' object is not iterable
In [40]:
s = set()
s.update('10')
s
Out[40]:
{'0', '1'}
# add() vs update() :-¶
In [42]:
# add() ---> to add single item
# update() ---> to add multiple items from the given sequence
In [43]:
s = set('mississippi')
s
Out[43]:
{'i', 'm', 'p', 's'}
In [44]:
s = set()
s.update(10,)
print(s)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[44], line 2 1 s = set() ----> 2 s.update(10,) 3 print(s) TypeError: 'int' object is not iterable
In [45]:
s = set()
s.update((10,))
print(s)
{10}
In [48]:
s = set()
s
Out[48]:
set()
In [49]:
s.add(10)
s
Out[49]:
{10}
In [50]:
s.add(10, 20, 30)
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[50], line 1 ----> 1 s.add(10, 20, 30) 2 s TypeError: set.add() takes exactly one argument (3 given)
In [51]:
s.update(10)
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[51], line 1 ----> 1 s.update(10) 2 s TypeError: 'int' object is not iterable
In [52]:
s.update(range(1, 11), range(11, 20))
s
Out[52]:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
In [54]:
s.add(range(1, 10))
s
Out[54]:
{1,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
2,
3,
4,
5,
6,
7,
8,
9,
range(1, 10)}
In [55]:
# In set every element should be hashable.
In [56]:
# List is not hashable but tuple is hashable
In [57]:
s = set()
s.add([10, 20, 30])
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[57], line 2 1 s = set() ----> 2 s.add([10, 20, 30]) 3 s TypeError: unhashable type: 'list'
In [58]:
s = set()
s.add((10, 20, 30))
s
Out[58]:
{(10, 20, 30)}
In [59]:
s = set()
s.add(range(0, 9))
s
Out[59]:
{range(0, 9)}
In [60]:
s = set()
s.update(range(0, 9))
s
Out[60]:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
In [61]:
l = [10,20,30]
print(l)
l.append(40)
print(l)
l.insert(1, 50)
print(l)
[10, 20, 30] [10, 20, 30, 40] [10, 50, 20, 30, 40]
In [62]:
s.add(10)
# Internally PVM will store elements of set based on hashing.
# str is hashable type
# int is hashable type
# list is not hashable
In [63]:
s = set()
s.add(10)
s
Out[63]:
{10}
In [64]:
s = set()
s.add(10.5)
s
Out[64]:
{10.5}
In [65]:
s = set()
s.add("durga")
s
Out[65]:
{'durga'}
In [66]:
s = set()
s.add([10, 20, 30])
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[66], line 2 1 s = set() ----> 2 s.add([10, 20, 30]) 3 s TypeError: unhashable type: 'list'
In [67]:
s = set()
s.add((10, 20, 30))
s
Out[67]:
{(10, 20, 30)}
In [68]:
# If our frequent operation is search then set is the best choice.
In [69]:
# s = set(list) ---> in this we won;t get any error because we are not adding list object directly, we are adding elements present in the list.
# s.update(list) ---> in this we won;t get any error because we are not adding list object directly, we are adding elements present in the list.
# s.add(list) ---> we are getting error becuase we are adding list object directly to the set.
In [70]:
s = set()
s.add([10, 20, 30]) # we are adding list object to the set
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[70], line 2 1 s = set() ----> 2 s.add([10, 20, 30]) 3 s TypeError: unhashable type: 'list'
In [71]:
s = set()
s.update([10, 20, 30]) # we are adding elements present in the list to the set
s
Out[71]:
{10, 20, 30}
In [72]:
s = set([10, 20, 30])
s
Out[72]:
{10, 20, 30}
In [73]:
s = set()
s.update([10, 20, [30, 40]])
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[73], line 2 1 s = set() ----> 2 s.update([10, 20, [30, 40]]) 3 s TypeError: unhashable type: 'list'
In [74]:
# 3. remove() elements :-
In [75]:
# s.pop() ---> it removes and returns some random element from the set
In [81]:
s = {10, 50, 40, 20, 5, 0, 5}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
{0, 50, 20, 5, 40, 10}
0
50
20
5
40
In [83]:
s = {10, 50, 40, 20, 5, 0, 5}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
{0, 50, 20, 5, 40, 10}
0
50
20
5
40
10
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[83], line 10 8 print(s.pop()) 9 print(s.pop()) ---> 10 print(s.pop()) KeyError: 'pop from an empty set'
In [84]:
s = {10, 50, 40, 20, 5, 0, 5}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
if len(s) != 0:
print(s.pop())
{0, 50, 20, 5, 40, 10}
0
50
20
5
40
10
In [87]:
s = {10, 20, 30, 10, 20, 30, 40, 50, 60, 70, 80, 10, 20, 30, 40, 50}
while len(s) != 0:
n = s.pop()
print("Sending SMS to Mobile Number:", n)
Sending SMS to Mobile Number: 70 Sending SMS to Mobile Number: 40 Sending SMS to Mobile Number: 10 Sending SMS to Mobile Number: 80 Sending SMS to Mobile Number: 50 Sending SMS to Mobile Number: 20 Sending SMS to Mobile Number: 60 Sending SMS to Mobile Number: 30
In [93]:
# 4. remove(x) :-
# It removes the specified element
# If the specified element is not available then we will get KeyError
In [90]:
s = {10, 20, 30}
s.remove(20)
print(s)
{10, 30}
In [91]:
s = {10, 20, 30}
s.remove(40)
print(s)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[91], line 2 1 s = {10, 20, 30} ----> 2 s.remove(40) 3 print(s) KeyError: 40
In [92]:
s = {10, 20, 30}
if 40 in s:
s.remove(40)
print(s)
{10, 20, 30}
In [94]:
# 5. s.discard(x) :-
# It removes the specified element
# If the specified element is not available then we won't get any Error.
In [95]:
s = {10, 20, 30}
s.discard(40)
print(s)
{10, 20, 30}
In [96]:
s = {10, 20, 30}
s.discard(40)
s.discard(20)
s.discard(90)
s.discard(70)
s.discard(30)
print(s)
{10}
In [98]:
# remove(x) and discard(x) and pop() :-
In [99]:
# 6. s.clear() :-
# To remove all elements from the set
In [100]:
s = {10, 20, 50, 560, 54, 40, 30}
print(s)
s.clear()
print(s)
{560, 50, 20, 54, 40, 10, 30}
set()
In [101]:
# s1 = s ===> aliasing duplicate reference variable creation
# s1 = s.copy() ===> cloning duplicate set object creation
In [102]:
s = {10, 20, 30}
s1 = s
print(id(s))
print(id(s1))
2551548162144 2551548162144
In [103]:
s = {10, 20, 30}
s1 = s.copy()
print(id(s))
print(id(s1))
2551548164160 2551548159456
In [ ]:
# Mathematical Operations on the Set :-¶
In [7]:
# 1. union() ---> A | B
# 2. intersection() ---> A & B
# 3. difference() ---> A - B
# 4. symmetric_difference() ---> A ^ B
In [2]:
s1 = {1, 2, 3}
s2 = {4, 5, 6}
print(s1)
print(s2)
{1, 2, 3}
{4, 5, 6}
In [3]:
s3 = s1 + s2
print(s3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 1 ----> 1 s3 = s1 + s2 2 print(s3) TypeError: unsupported operand type(s) for +: 'set' and 'set'
In [4]:
s3 = s1 * s2
print(s3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 1 ----> 1 s3 = s1 * s2 2 print(s3) TypeError: unsupported operand type(s) for *: 'set' and 'set'
In [8]:
# 1. union() :-
# x.union(y) ===> It returns all elements present in both x and y
# x | y
In [15]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.union(y))
print(x | y)
print(y.union(x))
print(y | x)
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
In [16]:
# 2. intersection() :-
# common elements
# x.intersection(y)
# x & y
In [17]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.intersection(y))
print(x & y)
print(y.intersection(x))
print(y & x)
{40, 30}
{40, 30}
{40, 30}
{40, 30}
In [18]:
# 3. difference() :-
# x.difference(y)
# x - y
# The elements present in x but not in y
In [21]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.difference(y))
print(x - y)
print(y.difference(x))
print(y - x)
{10, 20}
{10, 20}
{50, 60}
{50, 60}
In [24]:
# 3. symmetric_difference() :-
# x.symmetric_difference(y)
# x ^ y
# The elements present in either x or y butu not in both
In [23]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.symmetric_difference(y))
print(x ^ y)
print(y.symmetric_difference(x))
print(y ^ x)
{10, 50, 20, 60}
{10, 50, 20, 60}
{10, 50, 20, 60}
{10, 50, 20, 60}
# Membership Operator :-¶
In [26]:
# in, not in
In [28]:
x = {10, 20, 30, 40}
print(x)
{40, 10, 20, 30}
In [29]:
print(10 in x)
True
In [30]:
print(50 in x)
False
In [31]:
print(50 not in x)
True
# Comprehension :-¶
In [3]:
# list ---> applicable
# tuple ---> not applicable
# set ---> applicable
In [4]:
s = {x * x for x in range(1, 6)}
print(type(s))
print(s)
<class 'set'>
{1, 4, 9, 16, 25}
In [5]:
s = {2**x for x in range(1, 6)}
print(type(s))
print(s)
<class 'set'>
{32, 2, 4, 8, 16}
In [1]:
s1 = {10, 20, 30}
s2 = {20, 30, 10}
print(s1 is s2)
print(s1 == s2)
False True
In [7]:
s1 = {10, 20, 30}
s2 = {10, 20, 30}
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873356064 2947873352704
In [13]:
s1 = {10, 20, 30}
s2 = s1
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
True True 2947873356064 2947873356064
In [9]:
s1 = {10, 20, 30}
s2 = s1.copy()
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873357408 2947873352704
In [10]:
s1 = [10, 20, 30]
s2 = [10, 20, 30]
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873771776 2947873774592
In [12]:
s1 = (10, 20, 30)
s2 = (10, 20, 30)
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873830336 2947873799232
In [14]:
# For set order is not important
# indexing and slicing concepts are not applicable
In [15]:
s = {10, 20, 30}
print(s)
{10, 20, 30}
In [16]:
s[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[16], line 1 ----> 1 s[0] TypeError: 'set' object is not subscriptable
In [17]:
s = [10, 20, 30]
print(id(s))
s = [20, 30, 10]
print(id(s))
2947873665088 2947879642112
In [19]:
# WAP to delete duplicates present in the list?
In [22]:
l = eval(input("Enter a list of values:"))
print(l)
s = set(l)
print(s)
[4646, 64, 546, 46, 464, 46]
{64, 546, 4646, 46, 464}
In [23]:
l = eval(input("Enter a list of values:"))
print(l)
l1 = []
for x in l:
if x not in l1:
l1.append(x)
print(l1)
[46, 22, 21, 12, 12, 45, 45, 65, 65, 85, 95, 85, 95] [46, 22, 21, 12, 45, 65, 85, 95]
In [ ]:
# # Dictionary Data Structure :-¶
In [3]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [7]:
# keys ---> 100, 200, 300
# values ---> 'durga', 'ravi', 'shiva'
# duplicate keys are not allowed, but values can be duplicated.
# If we are trying to add key-value pair but key already present, then old value will be replaced with new value.
# order is not applicable and all elements will be inserted based on hash of keys.
# indexing and slicing concepts are not applicable.
# for keys and values we can take heterogeneous objects.
# dict is mutable.
# dict is growable.
In [6]:
d = {100: "durga", "ravi": 200, True: "shiva"}
print(d)
{100: 'durga', 'ravi': 200, True: 'shiva'}
# How to Create Dictionary :-¶
In [16]:
# If we don't know data :-
In [17]:
d = {}
print(type(d))
# or
d = dict()
print(type(d))
<class 'dict'> <class 'dict'>
In [15]:
# d[key] = value ===>
# The provided key-valule pair will be added to the dict
# If the dspecified key is already available then old value will be replaced with new value.
# d = {key1:value1, key2:value2, key3:value3}
In [13]:
d = {}
print(d)
d[100] = "durga"
d[200] = "shiva"
d[300] = "ravi"
print(d)
{}
{100: 'durga', 200: 'shiva', 300: 'ravi'}
In [14]:
d[100] = "pavan"
print(d)
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
In [18]:
d = {1, 2, 3 : 'a', 'b', 'c'}
Cell In[18], line 1 d = {1, 2, 3 : 'a', 'b', 'c'} ^ SyntaxError: invalid syntax
# Access Data From the Dictionary :-¶
In [24]:
# By using key we can access the corresponding value.
In [20]:
d = {100: "pavan", 200: "shiva", 300: "ravi"}
print(d)
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
In [21]:
print(d[200])
shiva
In [22]:
print(d[100])
pavan
In [23]:
print(d[500])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[23], line 1 ----> 1 print(d[500]) KeyError: 500
In [26]:
# Using value can we get key?
In [28]:
d = {100: "pavan", 200: "shiva", 300: "ravi"}
print(d)
key = int(input("Enter key to find corresponding value:"))
if key in d:
print(d[key])
else:
print("Specified key not available:", key)
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
Specified key not available: 352
In [ ]:
In [1]:
d = {100: "pavan", 200: "shiva", 300: "ravi"}
print(d)
print(d[200])
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
shiva
In [2]:
# Quest: WAP to enter name and marks in a dictionary and display information on the screen?
In [4]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
if option.lower() == "n":
break
elif option.lower() == 'y':
continue
else:
print('Invalid Input to Continue')
break
print(d)
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Invalid Input to Continue
{'asdadf': '54', 'amsdka': '95', 'safas': '12', 'dsafads': '56'}
In [1]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
while True:
if option.lower() == "n":
option = "n"
break
elif option.lower() == "y":
option = "y"
break
else:
option = input("Your Entered option is Invalid, Please Choose Correct option [Y|N]:")
if option == "n":
break
print(d)
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
{'ram': '95', 'han': '85', 'nksdnf': "52'", 'dsaf': '5654'}
In [2]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
while True:
if option.lower() in ["y", "n"]:
break
else:
option = input(
"Your Entered option is Invalid, Please Choose Correct option [Y|N]:"
)
if option == "n":
break
print(d)
Student record inserted Successfully
Student record inserted Successfully
{'ad': '54', 'asd': '5'}
In [8]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
while True:
if option.lower() not in ["y", "n"]:
option = input(
"Your Entered option is Invalid, Please Choose Correct option [Y|N]:"
)
else:
break
if option == "n":
break
print(d)
for x in d:
print("{}\t{}".format(x, d[x]))
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
{'ram': '52', 'shyam': '95', 'barry': '96'}
ram 52
shyam 95
barry 96
In [7]:
d = {}
while len(d) < 5:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
print(d)
for x in d:
print("{}\t{}".format(x, d[x]))
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
{'ram': '10', 'shyam': '30', 'ravi': '65', 'harry': '94', 'barry': '82'}
ram 10
shyam 30
ravi 65
harry 94
barry 82
# Update Dictionary :-¶
In [10]:
# d = {}
# d[key] = value
# If the specified key is not already available, then key-value will be added.
# If the specified key is already available, then olde value will be replaced with new value.
In [11]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
d[400] = "pavan"
print(d)
d[200] = "harry"
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
{100: 'durga', 200: 'harry', 300: 'shiva', 400: 'pavan'}
# Delete Elements from Dictionary :-¶
In [15]:
# del d[key]
# If the specified key is available, then total entry will be deleted.
# If the specified key is not available, then we will get KeyError.
In [13]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [14]:
del d[100]
print(d)
{200: 'ravi', 300: 'shiva'}
In [16]:
del d[400]
print(d)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[16], line 1 ----> 1 del d[400] 2 print(d) KeyError: 400
In [17]:
if 400 in d:
del d[400]
print(d)
{200: 'ravi', 300: 'shiva'}
In [19]:
# To remove all the entries :-
# d.clear()
# del d
In [20]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [21]:
d.clear()
print(d)
{}
In [24]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [25]:
del d
print(d)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[25], line 2 1 del d ----> 2 print(d) NameError: name 'd' is not defined
# Important Methods and Functions related to Dictionary :-¶
In [27]:
# 1. dict() :-
In [29]:
d = dict()
print(d)
print(type(d))
{}
<class 'dict'>
In [30]:
d = dict({100: "ram", 200: "durga"})
print(d)
print(type(d))
{100: 'ram', 200: 'durga'}
<class 'dict'>
In [31]:
# [(100, 'durga'), (200, 'shiva'), (300, 'ravi')] ---> List of Tuples
In [32]:
d = dict([(100, "durga"), (200, "shiva"), (300, "ravi")])
print(d)
print(type(d))
{100: 'durga', 200: 'shiva', 300: 'ravi'}
<class 'dict'>
In [33]:
d = dict(((100, "durga"), (200, "shiva"), (300, "ravi")))
print(d)
print(type(d))
{100: 'durga', 200: 'shiva', 300: 'ravi'}
<class 'dict'>
In [34]:
d = dict([[100, "durga"], [200, "shiva"], [300, "ravi"]])
print(d)
print(type(d))
{100: 'durga', 200: 'shiva', 300: 'ravi'}
<class 'dict'>
In [35]:
d = dict({[100, "durga"], [200, "shiva"], [300, "ravi"]})
print(d)
print(type(d))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[35], line 1 ----> 1 d = dict({[100, "durga"], [200, "shiva"], [300, "ravi"]}) 2 print(d) 3 print(type(d)) TypeError: unhashable type: 'list'
In [36]:
d = dict({(100, "durga"), (200, "shiva"), (300, "ravi")})
print(d)
print(type(d))
{300: 'ravi', 100: 'durga', 200: 'shiva'}
<class 'dict'>
In [39]:
# 2. len() :-
# returns the number of items in the dictionary
# item ---> key-value pair
In [40]:
d = dict({(100, "durga"), (200, "shiva"), (300, "ravi")})
print(d)
print(len(d))
{300: 'ravi', 100: 'durga', 200: 'shiva'}
3
In [47]:
# 3. get(key) :-
# returns the corresponding value.
# If specified key not available then None
# d[key] ---> KeyError
# d.get(key) ---> None
# d.get(key, default_value)
In [50]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [44]:
print(d.get(100))
durga
In [45]:
print(d.get(200))
ravi
In [46]:
print(d.get(900))
None
In [48]:
print(d.get(900, 'no value'))
no value
In [ ]:
In [2]:
# 5. pop() :-
# d.pop(key)
# remove item(key-value pair) associated with the specified key and returns the corresponding value.
# If the specified key not already available then we will get KeyError.
In [4]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [5]:
print(d.pop())
print(d)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[5], line 1 ----> 1 print(d.pop()) 2 print(d) TypeError: pop expected at least 1 argument, got 0
In [6]:
print(d.pop(200))
print(d)
ravi
{100: 'durga', 300: 'shiva'}
In [7]:
print(d.pop(500))
print(d)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[7], line 1 ----> 1 print(d.pop(500)) 2 print(d) KeyError: 500
In [14]:
# 6. popitem() :-
# d.popitem()
# It will remove an arbitrary item from the dict and returns it.
# If the dict is empty then we get KeyError
In [9]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [10]:
print(d.popitem())
print(d)
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
In [11]:
print(d.popitem())
print(d)
(200, 'ravi')
{100: 'durga'}
In [12]:
print(d.popitem())
print(d)
(100, 'durga')
{}
In [13]:
print(d.popitem())
print(d)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[13], line 1 ----> 1 print(d.popitem()) 2 print(d) KeyError: 'popitem(): dictionary is empty'
In [22]:
# 7. keys() :-
# d.keys()
In [23]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
print(d)
{'A': 100, 'B': 110, 'C': 120, 'D': 130, 'E': 140, 'F': 150, 'G': 160, 'H': 170, 'I': 180, 'J': 190, 'K': 200, 'L': 210, 'M': 220, 'N': 230, 'O': 240, 'P': 250, 'Q': 260, 'R': 270, 'S': 280, 'T': 290, 'U': 300, 'V': 310, 'W': 320, 'X': 330, 'Y': 340, 'Z': 350}
In [24]:
while len(d) != 0:
print('Processing item:', d.popitem())
Processing item: ('Z', 350)
Processing item: ('Y', 340)
Processing item: ('X', 330)
Processing item: ('W', 320)
Processing item: ('V', 310)
Processing item: ('U', 300)
Processing item: ('T', 290)
Processing item: ('S', 280)
Processing item: ('R', 270)
Processing item: ('Q', 260)
Processing item: ('P', 250)
Processing item: ('O', 240)
Processing item: ('N', 230)
Processing item: ('M', 220)
Processing item: ('L', 210)
Processing item: ('K', 200)
Processing item: ('J', 190)
Processing item: ('I', 180)
Processing item: ('H', 170)
Processing item: ('G', 160)
Processing item: ('F', 150)
Processing item: ('E', 140)
Processing item: ('D', 130)
Processing item: ('C', 120)
Processing item: ('B', 110)
Processing item: ('A', 100)
In [25]:
print(d)
{}
In [26]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
k = d.keys()
print(type(k))
print(k)
for k1 in k:
print(k1)
<class 'dict_keys'> dict_keys(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
In [29]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
for k1 in d.keys():
print(k1)
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
In [30]:
# 8. values() :-
# d.values()
In [32]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
print(d.values())
dict_values([100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350])
In [33]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
print(d.values())
for v in d.values():
print(v)
dict_values([100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350]) 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300 310 320 330 340 350
In [34]:
d = {100: "durga", 200: "durga", 300: "durga"}
for v in d.values():
print(v)
durga durga durga
In [36]:
# 9. items() :-
# d.items()
# item ---> key-value pair
In [39]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
i = d.items()
print(type(i))
print(i)
<class 'dict_items'> dict_items([(100, 'durga'), (200, 'ravi'), (300, 'shiva')])
In [40]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
for x in d.items():
print(x)
(100, 'durga') (200, 'ravi') (300, 'shiva')
In [43]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
for k in d.keys():
print("Key:", k)
for v in d.values():
print("Value:", v)
for k, v in d.items():
print("{}:{}".format(k, v))
Key: 100 Key: 200 Key: 300 Value: durga Value: ravi Value: shiva 100:durga 200:ravi 300:shiva
In [44]:
# 10. setdefault() :-
# d.setdefault(k, v)
# If the specified key available, then it returnsthe corresponding value.
# If the specified key not available, then the provided key-value pair will be added as a new item to the dictionary.
In [48]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [53]:
print(d.setdefault(100, "sunny"))
d.setdefault(100, "sunny")
print(d)
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 500: 'bunny'}
In [54]:
print(d.setdefault(500, "bunny"))
d.setdefault(500, "bunny")
print(d)
bunny
{100: 'durga', 200: 'ravi', 300: 'shiva', 500: 'bunny'}
In [66]:
# 11. update() :-
In [55]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = {400: "sunny", 500: "bunny", 600: "harry"}
print(d1)
print(d2)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{400: 'sunny', 500: 'bunny', 600: 'harry'}
In [56]:
d1.update(d2)
print(d1)
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'sunny', 500: 'bunny', 600: 'harry'}
In [57]:
print(d2)
{400: 'sunny', 500: 'bunny', 600: 'harry'}
In [58]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = {400: "sunny", 500: "bunny", 100: "harry"}
print(d1)
print(d2)
d1.update(d2)
print(d1)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{400: 'sunny', 500: 'bunny', 100: 'harry'}
{100: 'harry', 200: 'ravi', 300: 'shiva', 400: 'sunny', 500: 'bunny'}
In [60]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = {400: "sunny", 500: "bunny", 100: "harry"}
print(d1)
print(d2)
d1.update(d2)
d2.update(d1)
print(d1)
print(d2)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{400: 'sunny', 500: 'bunny', 100: 'harry'}
{100: 'harry', 200: 'ravi', 300: 'shiva', 400: 'sunny', 500: 'bunny'}
{400: 'sunny', 500: 'bunny', 100: 'harry', 200: 'ravi', 300: 'shiva'}
In [61]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1.copy()
print(id(d1))
print(id(d2))
1543898304192 1543899138368
In [62]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1
print(id(d1))
print(id(d2))
1543892330624 1543892330624
In [63]:
# d2 = d1 ===> duplicate reference variable and aliasing
# d2 = d1.copy() ===> duplicate object and cloning
In [64]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1.copy()
print(id(d1))
print(id(d2))
print(d1 is d2)
1543898481920 1543892379136 False
In [65]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1
print(id(d1))
print(id(d2))
print(d1 is d2)
1543898489856 1543898489856 True
In [67]:
# 1. dict()
# 2. len()
# 3. clear()
# 4. get()
# d.get(key)
# d.get(key, default_value)
# 5. pop()
# 6. popitem()
# 7. keys()
# 8. values()
# 9. items()
# 10. setdefault()
# 11. update()
# 12. copy()
# d[key] = value
# del d[key]
In [69]:
# Ques: WAP to take dictionary from the keyboard and print the sum of values?
In [72]:
d = eval(input("Enter Dictionary:"))
print(d)
sum(d.values())
print("The Sum:", sum(d.values()))
{'a': 10, 'b': 20, 'v': 50}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[72], line 3 1 d = eval(input("Enter Dictionary:")) 2 print(d) ----> 3 sum(d.values()) 5 print("The Sum:", sum(d.values())) TypeError: 'int' object is not callable
In [71]:
d = eval(input("Enter Dictionary:"))
print(d)
sum = 0
for v in d.values():
sum = sum + v
print("The Sum:", sum)
The Sum: 60
In [73]:
# Ques: WAP to find the number of occurreneces of each letter present in the given string?
In [78]:
s = input("Enter any word:")
print(s)
d = {}
for ch in s:
if ch in d:
d[ch] = d[ch] + 1
else:
d[ch] = 1
print(d)
mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
In [80]:
s = input("Enter any word:")
print(s)
d = {}
for ch in s:
d[ch] = d.get(ch, 0) + 1
print(d)
for k, v in d.items():
print("{} occurs {} times".format(k, v))
mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
m occurs 1 times
i occurs 4 times
s occurs 4 times
p occurs 2 times
In [81]:
s = input("Enter any word:")
print(s)
d = {}
for ch in s:
d[ch] = d.get(ch, 0) + 1
print(d)
for k, v in sorted(d.items()):
print("{} occurs {} times".format(k, v))
mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
i occurs 4 times
m occurs 1 times
p occurs 2 times
s occurs 4 times
In [82]:
s = input("Enter any word:")
print(s)
vowels = {'a','e','i','o','u'}
d = {}
for ch in s:
if ch in vowels:
d[ch] = d.get(ch, 0) + 1
print(d)
for k, v in sorted(d.items()):
print("{} occurs {} times".format(k, v))
missipkdanskbfked vm,asd kjcvvhadsukc shad cadsjvgcjakevld jds
{'i': 2, 'a': 6, 'e': 2, 'u': 1}
a occurs 6 times
e occurs 2 times
i occurs 2 times
u occurs 1 times
In [ ]:
# # Merging of Collections :-¶
In [2]:
l1 = [10, 20, 30]
l2 = [40, 50, 60]
l3 = l1 + l2
print(l3)
[10, 20, 30, 40, 50, 60]
In [4]:
t1 = (10, 20, 30)
t2 = (40, 50, 60)
t3 = t1 + t2
print(t3)
(10, 20, 30, 40, 50, 60)
In [6]:
# List and Tuple ---> Apply
# Set and Dictionary ---> Not Apply
In [7]:
l1 = [10, 20, 30]
l2 = [40, 50, 60]
l3 = [*l1, *l2]
print(l3)
[10, 20, 30, 40, 50, 60]
In [8]:
l1 = (10, 20, 30)
l2 = (40, 50, 60)
l3 = (*l1, *l2)
print(l3)
(10, 20, 30, 40, 50, 60)
In [9]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s3 = s1 + s2
print(s3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 4 1 s1 = {10, 20, 30} 2 s2 = {40, 50, 60} ----> 4 s3 = s1 + s2 5 print(s3) TypeError: unsupported operand type(s) for +: 'set' and 'set'
In [10]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s3 = {*s1, *s2}
print(s3)
{50, 20, 40, 10, 60, 30}
In [11]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s = {"A", "B", "C"}
s3 = {*s1, *s2, *s}
print(s3)
{40, 10, 50, 'C', 20, 'A', 'B', 60, 30}
In [12]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s = {"A", "B", "C"}
l = [*s1, *s2, *s]
print(l)
[10, 20, 30, 40, 50, 60, 'C', 'B', 'A']
In [13]:
s1 = {10, 20, 30}
s2 = (40, 50, 60)
s = ["A", "B", "C"]
list = [*s1, *s2, *s]
print(list)
[10, 20, 30, 40, 50, 60, 'A', 'B', 'C']
In [14]:
s1 = {10, 20, 30}
s2 = (40, 50, 60)
s = ["A", "B", "C"]
tuple = (*s1, *s2, *s)
print(tuple)
(10, 20, 30, 40, 50, 60, 'A', 'B', 'C')
In [16]:
s1 = {10, 20, 30}
s2 = (40, 50, 60)
s = ["A", "B", "C"]
set = {*s1, *s2, *s}
print(set)
{40, 10, 50, 'C', 20, 'A', 'B', 60, 30}
In [17]:
d1 = {100: "A", 200: "B"}
d2 = {300: "C", 400: "D"}
d3 = {500: "E", 600: "F"}
result = {}
print(result)
{}
In [18]:
result = {**d1, **d2, **d3}
print(result)
{100: 'A', 200: 'B', 300: 'C', 400: 'D', 500: 'E', 600: 'F'}
In [19]:
result = {*d1, *d2, *d3}
print(result)
{400, 100, 500, 200, 600, 300}
In [20]:
result = {*d1.values(), *d2.values(), *d3.values()}
print(result)
{'C', 'D', 'F', 'E', 'B', 'A'}
In [22]:
# # Limitations for + Operator :-
# 1. Applicable only for list, tuple but not for set and dict
# 2. Compulsory both arguments should be same type.
# # Nested Collections :-¶
In [24]:
# Collection inside Collection
# Django, DRF
# inside list, we can take tuple
# inside dict, we can take another dict
In [25]:
l = [(10, 20, 30), (40, 50, 60)]
print(l)
[(10, 20, 30), (40, 50, 60)]
In [26]:
print(l[0][1])
20
In [27]:
print(l[1][2])
60
In [28]:
d = {
"cars": ("Innova", "Honda", "BMW"),
"mobiles": ("Samsung", "Nokia", "Iphone"),
}
In [33]:
print(d["cars"])
('Innova', 'Honda', 'BMW')
In [32]:
print(d["cars"][1])
Honda
In [31]:
print(d.get("cars")[1])
Honda
In [35]:
# To display all mobile names
for mobile in d['mobiles']:
print(mobile)
Samsung Nokia Iphone
In [37]:
# # Two Restrictions :-
# Every element isnide set should be hashable.
# Hence we cannot list object as element in set.
# Every key inside dictionary should be hashable.
# For the key we cannot take list object.
In [ ]:
In [1]:
# Ques: Write a program to accept student name and marks from the keyboard and with that data creates a dictionary. Also display student marks by taking student name as input?
In [2]:
n = int(input("Enter Number of Students:"))
d = {}
while len(d) <= n:
name = input("Enter Student Name:")
marks = int(input("Enter Student Marks:"))
d[name] = marks
print("All Students Data Inserted")
print(d)
while True:
name = input("Enter Student Name to get Marks:")
if name in d:
print("The Marks of {}:{}".format(name, d.get(name)))
else:
print("Student Not Found")
option = input("Do you want to find another Student Marks [Yes|No]:")
while option.lower() not in ["yes", "no"]:
option = input("Invalid Option, Please choose Valid Option [Yes|No]:")
if option.lower() == "no":
break
print('Thanks for Using Our Application')
All Students Data Inserted
{'ram': 85, 'shyam': 93, 'harry': 75, 'pavan': 72}
Student Not Found
Student Not Found
The Marks of ram:85
Thanks for Using Our Application
# Dictionary Comprehension :-¶
In [4]:
# List ---> Applicable
# Tuple ---> Not Applicable
# Set ---> Applicabel
# Dict ---> Applicable
In [6]:
l = [x * x for x in range(1, 6)]
print(l)
[1, 4, 9, 16, 25]
In [9]:
# key:value
# {1:1, 2:4, 3:9, 4:16, 5:25}
# d = {key:value for x in range(1,6)}
In [12]:
d = {x: x * x for x in range(1, 6)}
print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
In [11]:
d = {x: x * 2 for x in range(1, 6)}
print(d)
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
In [13]:
d = {x: chr(64 + x) for x in range(1, 27)}
print(d)
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z'}
In [ ]:
In [1]:
# # Implementation of Supermarket Dictionary :-
In [2]:
# supermarket has multiple stores
# Every store has a name
# Every store has multiple items
# Every item has name and quantity
In [3]:
# key-value
# for key ---> hashable
# for value ---> we can take anything
In [34]:
supermarket = {
"store1": {
"name": "DURGA GENERAL STORE",
"items": [
{"name": "soap", "quantity": 20},
{"name": "brush", "quantity": 30},
{"name": "paste", "quantity": 40},
],
},
"store2": {
"name": "SUNNY BOOK STORE",
"items": [
{"name": "Python", "quantity": 5},
{"name": "Django", "quantity": 15},
{"name": "Devops", "quantity": 25},
{"name": "Django", "quantity": 65},
],
},
}
In [35]:
print(supermarket)
{'store1': {'name': 'DURGA GENERAL STORE', 'items': [{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]}, 'store2': {'name': 'SUNNY BOOK STORE', 'items': [{'name': 'Python', 'quantity': 5}, {'name': 'Django', 'quantity': 15}, {'name': 'Devops', 'quantity': 25}, {'name': 'Django', 'quantity': 65}]}}
In [36]:
# To print name of store1
In [37]:
print(supermarket['store1'])
{'name': 'DURGA GENERAL STORE', 'items': [{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]}
In [38]:
print(supermarket['store1']['name'])
DURGA GENERAL STORE
In [39]:
print(supermarket.get('store1'))
{'name': 'DURGA GENERAL STORE', 'items': [{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]}
In [40]:
print(supermarket.get('store1').get('name'))
DURGA GENERAL STORE
In [41]:
# To print names of all items present in store1
In [42]:
print(supermarket['store1']['items'])
[{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]
In [43]:
print(supermarket.get('store1').get('items'))
[{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]
In [44]:
for d in supermarket['store1']['items']:
print(d['name'])
soap brush paste
In [45]:
for d in supermarket.get('store1').get('items'):
print(d.get('name'))
soap brush paste
In [46]:
for d in supermarket.get('store1').get('items'):
print(d)
{'name': 'soap', 'quantity': 20}
{'name': 'brush', 'quantity': 30}
{'name': 'paste', 'quantity': 40}
In [47]:
# How many django books are available?
In [48]:
for d in supermarket["store2"]["items"]:
if d["name"] == "Django":
print("The Number of Django Books:", d["quantity"])
The Number of Django Books: 15 The Number of Django Books: 65
In [49]:
# Ques: Which of the following allowed in Python?
In [57]:
# 1. List inside List
# 2. Tuple inside List
# 3. List inside Tuple
# 4. Tuple inside Set
# 5. List inside Set ---> Invalid
# 6. Set inside Set ---> Invalid
# 7. List as key in Dict ---> Invalid
# 8. List as Value in Dict
# 9. Tuple as key in Dict
# 10. Tuple as Value in Dict
# 11. Set as key in Dict ---> Invalid
# 12. Set as Value in Dict
In [52]:
s = {10,20,[30,40]}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[52], line 1 ----> 1 s = {10,20,[30,40]} TypeError: unhashable type: 'list'
In [53]:
s = {10,20,{30,40}}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[53], line 1 ----> 1 s = {10,20,{30,40}} TypeError: unhashable type: 'set'
In [54]:
# # Note :-
# List, Set are not hashable types.
# Every element inside set should be hashable. Hence we cannot take list, ste inside set.
# Key of Dict should be hashable.
# Hence we cannot take list, set as inside dict.
In [58]:
# List is unhashable, but how list inside list is accepted
# In List and tuple, elements will be inserted based on order and index and PVM won't required any hash. Hence elements need not be hashable.
# But in set and dict, elements will be inserted based on hash. Hence elements should be hashable.
In [60]:
d = {[10, 20]: "ram"}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[60], line 1 ----> 1 d = {[10, 20]: "ram"} TypeError: unhashable type: 'list'
In [61]:
d = {(10, 20): "ram"}
In [62]:
d = {{10, 20}: "ram"}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[62], line 1 ----> 1 d = {{10, 20}: "ram"} TypeError: unhashable type: 'set'
In [ ]:
# # Functions :-¶
In [6]:
# DRY -- Principle
# Don't Repeat Yourself
# code reusability
In [30]:
def calc(a, b):
print("Sum:", a + b)
print("Product:", a * b)
print("Difference:", a - b)
print("Dividend:", a / b)
calc(10, 20)
calc(20, 30)
Sum: 30 Product: 200 Difference: -10 Dividend: 0.5 Sum: 50 Product: 600 Difference: -10 Dividend: 0.6666666666666666
In [8]:
# # Types of Functions :-
# 1. Built in Functions
# 2. User Defined Functions
# 1. Built in Functions :-¶
In [10]:
# predefined functions
# id()
# print()
# input()
# eval()
# len()
# 2. User Defined Functions :-¶
In [13]:
# syntax for user defined function :
# def function_name(parameters):
# ''' doc string '''
# business logic
# business logic
# business logic
# business logic
# return value
# def ---> mandatory
# return ---> optional
In [14]:
# def m2(a,b):
# some Code
In [15]:
# class Test:
# def m1(self):
# some code
In [16]:
# Functions inside class ---> Methods
In [17]:
# Ques: Write a function to print hello?
In [29]:
def wish(): # Defining a function
print("hello")
wish() # Calling a function
hello
In [22]:
wish()
print("hi")
wish()
print("hi")
wish()
print("hi")
wish()
hello hi hello hi hello hi hello
# Parameters :-¶
In [24]:
# Parameters are inputs to the function.
# If a function takes parameters, at the time of calling function, values.
In [31]:
def wish(name):
print("Hello {}, Good Morning!".format(name))
wish("Harry")
Hello Harry, Good Morning!
In [32]:
name = input("Enter Name:")
wish(name)
Hello Harry, Good Morning!
In [33]:
# Ques: WAP to take number as arguments and print its square value?
In [34]:
def squareIt(number):
print("The square of {} is : {}".format(number, number**2))
squareIt(4)
squareIt(5)
squareIt(6)
squareIt(7)
The square of 4 is : 16 The square of 5 is : 25 The square of 6 is : 36 The square of 7 is : 49
In [35]:
def add(x, y):
print("The Sum of {} and {} is : {}".format(x, y, x + y))
add(10, 20)
add(20, 30)
add(30, 40)
add(40, 50)
The Sum of 10 and 20 is : 30 The Sum of 20 and 30 is : 50 The Sum of 30 and 40 is : 70 The Sum of 40 and 50 is : 90
# Return Statements :-¶
In [37]:
# Ques: WAF to accept 2 numbers as input and return sum?
In [39]:
def add(x, y):
return x + y
result = add(10, 20)
print("Sum:", result)
Sum: 30
In [41]:
def add(x, y):
print('Calling add function...')
return x + y
add(10, 20)
Calling add function...
Out[41]:
30
In [42]:
def validate(mobile_number):
if len(mobile_number) == 10:
return True
else:
return False
mobile_number = input("Enter Mobile Number:")
result = validate(mobile_number)
print(result)
True
In [43]:
def f1():
print('Hello')
result = f1()
print(result)
Hello None
In [45]:
# Every Function in Python in return some value.
# If you are not returning any value then by default return value is None.
In [46]:
x = 10
print(id(x))
140709881824328
In [48]:
print(print(x))
10 None
In [49]:
# Ques: WAF to check whether the given number is even or odd?
In [50]:
def even_odd(x):
if x % 2 == 0:
print("It is even number")
else:
print("It is odd number")
even_odd(15)
even_odd(10)
It is odd number It is even number
In [51]:
even_odd(int(input('Enter Some Number to Check:')))
It is even number
In [52]:
def even_odd():
x = int(input("Enter some Number:"))
if x % 2 == 0:
print("It is even number")
else:
print("It is odd number")
even_odd()
It is odd number
In [53]:
def even_odd(x):
if x % 2 == 0:
return "It is even number"
else:
return "It is odd number"
result = even_odd(15)
print(result)
It is odd number
In [54]:
def show(sequence):
for x in sequence:
print(x)
show("durga")
show(range(1, 6))
d u r g a 1 2 3 4 5
In [55]:
# Ques: WAF to find Factorial of given number?
In [62]:
def factorial(x):
result = 1
while x >= 1:
result = result * x
x = x - 1
return result
for i in range(0, 11):
print("The Factorial of {} is : {}".format(i, factorial(i)))
The Factorial of 0 is : 1 The Factorial of 1 is : 1 The Factorial of 2 is : 2 The Factorial of 3 is : 6 The Factorial of 4 is : 24 The Factorial of 5 is : 120 The Factorial of 6 is : 720 The Factorial of 7 is : 5040 The Factorial of 8 is : 40320 The Factorial of 9 is : 362880 The Factorial of 10 is : 3628800
In [66]:
def factorial(x):
result = 1
while x >= 1:
result = result * x
x = x - 1
print("The Factorial of {} is : {}".format(x, result))
for i in range(0, 11):
factorial(i)
The Factorial of 0 is : 1 The Factorial of 0 is : 1 The Factorial of 0 is : 2 The Factorial of 0 is : 6 The Factorial of 0 is : 24 The Factorial of 0 is : 120 The Factorial of 0 is : 720 The Factorial of 0 is : 5040 The Factorial of 0 is : 40320 The Factorial of 0 is : 362880 The Factorial of 0 is : 3628800
In [69]:
def calc(a, b):
sum = a + b
sub = a - b
return sum, sub
x, y = calc(20, 10)
print(x, y)
print("Sum:", x)
print("Difference:", y)
30 10 Sum: 30 Difference: 10
In [70]:
x = calc(20, 10)
print(x)
(30, 10)
In [72]:
def calc(a, b):
sum = a + b
sub = a - b
return [sum, sub]
x, y = calc(20, 10)
print(x, y)
print("Sum:", x)
print("Difference:", y)
x = calc(20, 10)
print(x)
30 10 Sum: 30 Difference: 10 [30, 10]
In [ ]:
# Types of Arguments/Parameters :-¶
In [2]:
def f1(a, b): # Formal Parameters
pass
f1(10, 20) # Arguments
In [3]:
# 4 Types of Parameters/Arguments :-
# 1. Positional Arguments
# 2. Keyword Arguments
# 3. Default Arguments
# 4. Varable Length Arguments
# 1. Positional Arguments :-¶
In [6]:
def sub(a, b):
print(a - b)
In [7]:
sub(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[7], line 1 ----> 1 sub(10) TypeError: sub() missing 1 required positional argument: 'b'
In [11]:
sub(10, 20)
sub(20, 10)
# The number of arguments must be matched
# The order of arguments is important, The result may be changed if we change order
-10 10
In [12]:
sub(10, 20, 30)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[12], line 1 ----> 1 sub(10, 20, 30) TypeError: sub() takes 2 positional arguments but 3 were given
# 2. Keyword Arguments :-¶
In [38]:
# We have to pass argument values by keyword i.e by paramter name.
# The number of arguments must be matched.
# The order is not important.
In [29]:
def sub(a, b):
print(a - b)
sub(a=10, b=20)
-10
In [17]:
sub(a=10, b=20)
sub(b=20, a=10)
-10 -10
In [49]:
# # Note :-
# We can use both positional arguments and keyword arguments simultaneously, but first positional arguments then keyword arguments.
# But keyword arguments won't follow positional arguments.
# Key name should be case sensitive.
In [27]:
def sub(a, b):
print(a - b)
In [30]:
sub(a=10, b=20)
-10
In [28]:
sub(x=10, b=20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[28], line 1 ----> 1 sub(x=10, b=20) TypeError: sub() got an unexpected keyword argument 'x'
In [31]:
sub(10, b=20)
-10
In [32]:
sub(10, a=20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[32], line 1 ----> 1 sub(10, a=20) TypeError: sub() got multiple values for argument 'a'
In [33]:
sub(a=10, 20)
Cell In[33], line 1 sub(a=10, 20) ^ SyntaxError: positional argument follows keyword argument
In [34]:
sub(b=10, 20)
Cell In[34], line 1 sub(b=10, 20) ^ SyntaxError: positional argument follows keyword argument
In [36]:
def sub(a, b, c, d, e):
print(a - b)
sub(10, 20, 30, 40, e=10)
-10
In [37]:
sub(10, 20, 30, 40, d=10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[37], line 1 ----> 1 sub(10, 20, 30, 40, d=10) TypeError: sub() got multiple values for argument 'd'
In [39]:
sub(10, 20, c=30, d=40, e=10)
-10
In [40]:
sub(10, 20, d=40, e=10, c=30)
-10
In [42]:
def wish(name, msg):
print("Hello", name, msg)
In [43]:
wish("Durga", "Good Morning")
Hello Durga Good Morning
In [44]:
wish("Durga", msg="Good Morning")
Hello Durga Good Morning
In [45]:
wish(name ="Durga", "Good Morning")
Cell In[45], line 1 wish(name ="Durga", "Good Morning") ^ SyntaxError: positional argument follows keyword argument
In [46]:
wish(name="Durga", msg="Good Morning")
Hello Durga Good Morning
# 3. Default Arguments :-¶
In [50]:
def wish(name="Guest"):
print("Hello", name, "Good Morning")
In [51]:
wish()
Hello Guest Good Morning
In [53]:
wish('Durga')
Hello Durga Good Morning
In [54]:
# Positional arguments and keywords arguments we have to take at the time of calling.
# But default arguments at the time of declaration.
In [55]:
wish(name ='Durga')
Hello Durga Good Morning
In [56]:
def wish(name="Guest", msg="Good Morning"):
print("Hello", name, msg)
In [57]:
wish()
Hello Guest Good Morning
In [58]:
wish(name="Durga")
Hello Durga Good Morning
In [59]:
wish("Durga", msg="Good Evening")
Hello Durga Good Evening
In [60]:
wish("Good Evening")
Hello Good Evening Good Morning
In [61]:
wish(name="Durga", msg="Good Evening")
Hello Durga Good Evening
In [62]:
wish(msg="Good Evening")
Hello Guest Good Evening
In [63]:
wish(name="Durga", "Good Evening")
Cell In[63], line 1 wish(name="Durga", "Good Evening") ^ SyntaxError: positional argument follows keyword argument
In [64]:
def wish(name="Guest", msg="Good Morning"):
pass
In [65]:
def wish(name, msg="Good Morning"):
pass
In [66]:
def wish(name="Guest", msg):
pass
Cell In[66], line 1 def wish(name="Guest", msg): ^ SyntaxError: non-default argument follows default argument
In [67]:
# Default arguments should be last arguments. i.e after default arguments we cannot take non-default arguments.
In [68]:
def wish(msg, name="Guest"):
pass
# 4. Variable Length Arguments :-¶
In [105]:
# Varaible number of arguments: at the time of declaration/definition.
In [85]:
def f(*x):
print("The Type of x:", type(x))
print("The Number of arguments passed:", len(x))
In [86]:
f()
The Type of x: <class 'tuple'> The Number of arguments passed: 0
In [87]:
f(10)
The Type of x: <class 'tuple'> The Number of arguments passed: 1
In [88]:
f(10, 20)
The Type of x: <class 'tuple'> The Number of arguments passed: 2
In [89]:
f(10, 20, 30)
The Type of x: <class 'tuple'> The Number of arguments passed: 3
In [90]:
f(10, 20, 30, 40)
The Type of x: <class 'tuple'> The Number of arguments passed: 4
In [91]:
f(10, 20, 30, 40, 50, 60, 70, 80, 90)
The Type of x: <class 'tuple'> The Number of arguments passed: 9
In [92]:
def sum(*n):
total = 0
for n1 in n:
total = total + n1
print("Sum:", total)
In [93]:
sum(10)
Sum: 10
In [94]:
sum(10, 20)
Sum: 30
In [95]:
sum(10, 20, 30, 40, 50, 60)
Sum: 210
In [96]:
sum()
Sum: 0
In [97]:
def sum(*n):
for n1 in n:
print(n1)
In [98]:
sum(10, "durga")
10 durga
In [99]:
def sum(*n):
print(n)
sum(10, "durga")
(10, 'durga')
In [109]:
# We can use normal arguments and varaible length arguments simultaneously.
# We can take variable length argument anywhere.
In [101]:
def sum(n, *s):
print(n)
print(s)
In [102]:
sum(10, 20, 30, 40, 50)
10 (20, 30, 40, 50)
In [103]:
def sum(*s, n):
print(s)
print(n)
In [104]:
sum(10, 20, 30, 40, 50)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[104], line 1 ----> 1 sum(10, 20, 30, 40, 50) TypeError: sum() missing 1 required keyword-only argument: 'n'
In [108]:
sum(10, 20, 30, 40, 50, n=10)
(10, 20, 30, 40, 50) 10
In [110]:
# After variable lengtrh argument, if we are taking normal argument, we should provide value by using keyword only.
In [111]:
sum(10, 20, 30, 40, n=10, 50)
Cell In[111], line 1 sum(10, 20, 30, 40, n=10, 50) ^ SyntaxError: positional argument follows keyword argument
In [112]:
def sum(*s, n=0):
print(s)
print(n)
In [113]:
sum(10, 20, 30, 40, 50)
(10, 20, 30, 40, 50) 0
In [114]:
sum(10, 20, 30, 40, 50, n=60)
(10, 20, 30, 40, 50) 60
In [115]:
def sum(n=0, *s):
print(s)
print(n)
In [118]:
sum(10, 20, 30, 40, 50, n=60)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[118], line 1 ----> 1 sum(10, 20, 30, 40, 50, n=60) TypeError: sum() got multiple values for argument 'n'
In [119]:
sum(n=60, 10, 20, 30, 40, 50)
Cell In[119], line 1 sum(n=60, 10, 20, 30, 40, 50) ^ SyntaxError: positional argument follows keyword argument
In [120]:
sum(10, 20, 30, 40, 50)
(20, 30, 40, 50) 10
In [121]:
# After default arguments, we cannot take noraml arguments but we can take variable length arguments.
In [122]:
def sum(*m, *n):
print(m)
print(n)
Cell In[122], line 1 def sum(*m, *n): ^ SyntaxError: * argument may appear only once
In [123]:
# We cannot take more than one variable keyword argument.
In [124]:
def sum(*a, b, c, d, e):
pass
In [125]:
sum(1, 2, 3, 4, 5)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[125], line 1 ----> 1 sum(1, 2, 3, 4, 5) TypeError: sum() missing 4 required keyword-only arguments: 'b', 'c', 'd', and 'e'
In [ ]:
In [1]:
# 1. Positional Arguments
# 2. Keyword Arguments
# 3. Default Arguments
# 4. Variable Length Argumnets
In [3]:
# 1. Positional Arguments :-
# At the time of calling
# Order and Number are Important
In [4]:
def f1(a, b):
print(a - b)
f1(10, 20)
-10
In [7]:
# 2. Keyword Arguments :-
# At the time of calling
# Order/Position is not Important
In [6]:
def f1(a, b):
print(a - b)
f1(a=10, b=20)
-10
In [8]:
# We can use positional and keyword argumnets together but :
# First we should use positional argumnets and then keyword arguments.
In [9]:
# 3. Default Arguments :-
# At the time of declaration/creation.
# After taking default arguments, we cannot take normal arguments. But we can take variable length arguments.
In [11]:
def f1(a, b=0):
print(a - b)
f1(a=10)
f1(a=10, b=20)
10 -10
In [12]:
def f1(a=0, b):
print(a - b)
f1(a=10)
f1(a=10, b=20)
Cell In[12], line 1 def f1(a=0, b): ^ SyntaxError: non-default argument follows default argument
In [13]:
def f1(a=0, *b):
print(a - b)
f1(a=10)
f1(a=10, b=20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[13], line 5 1 def f1(a=0, *b): 2 print(a - b) ----> 5 f1(a=10) 6 f1(a=10, b=20) Cell In[13], line 2, in f1(a, *b) 1 def f1(a=0, *b): ----> 2 print(a - b) TypeError: unsupported operand type(s) for -: 'int' and 'tuple'
In [16]:
# 4. Variable Length Arguments :-
# At the time of declaration/creation
# We can take variable length arguments anywhere.
# But after variable length argument, if we are taking any normal argument, compulsory we should pass value by keyword.
# We can take only one variable-length argument.
In [15]:
def f1(*x):
print(x)
f1(10, 20, 30, 40)
(10, 20, 30, 40)
In [18]:
def f1(*x, y):
print(x)
print(y)
In [19]:
f1(10, 20, 30, 40)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[19], line 1 ----> 1 f1(10, 20, 30, 40) TypeError: f1() missing 1 required keyword-only argument: 'y'
In [20]:
f1(10, 20, 30, y=40)
(10, 20, 30) 40
In [21]:
def fn(*var1, var2):
print(var1)
print(var2)
fn(10, "durga", 10.5, True, var2=40)
(10, 'durga', 10.5, True) 40
In [22]:
# *x ---> We can provide any number of values for x and x will become tuple.
# *args
# **x ---> We can pass any number of key-value pairs and x will become dict.
# **kwargs
In [24]:
def display(**kwargs):
print(type(kwargs))
print(kwargs)
In [25]:
display(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[25], line 1 ----> 1 display(10) TypeError: display() takes 0 positional arguments but 1 was given
In [27]:
display(name="Durga", rollno=101, narks=90)
<class 'dict'>
{'name': 'Durga', 'rollno': 101, 'narks': 90}
In [28]:
def display(**kwargs):
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(name="Durga", rollno=101, narks=90)
name=Durga rollno=101 narks=90
In [30]:
# .items ---> provide list of items
In [31]:
def display(**kwargs):
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(name="Durga", rollno=101, narks=90)
dict_items([('name', 'Durga'), ('rollno', 101), ('narks', 90)])
name=Durga
rollno=101
narks=90
In [33]:
def display(*args, **kwargs):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90)
(10, 20, 30)
dict_items([('name', 'Durga'), ('rollno', 101), ('narks', 90)])
name=Durga
rollno=101
narks=90
In [35]:
def display(*args, **kwargs, x):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90)
Cell In[35], line 1 def display(*args, **kwargs, x): ^ SyntaxError: arguments cannot follow var-keyword argument
In [37]:
def display(*args, **kwargs, x=10):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90)
Cell In[37], line 1 def display(*args, **kwargs, x=10): ^ SyntaxError: arguments cannot follow var-keyword argument
In [42]:
# After varible length argument after **kwargs, it won't except any other type of argument.
In [43]:
def display(*args, **kwargs, x=10):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90, x=10)
Cell In[43], line 1 def display(*args, **kwargs, x=10): ^ SyntaxError: arguments cannot follow var-keyword argument
# Rules to Remember :-¶
In [44]:
# 1. After keyword arguments, we cannot take positional arguments.
# 2. After default arguments, we cannit take normal arguments, but we can take variable length arguments.
# 3. After Variable length arguments, if we are taking any normal argument, compulsory we should provide values by keyword only.
# 4. We can take atmost one varaible length argument.
# 5. **kwargs should be last arguments.
In [45]:
def f1(arg1, arg2, arg3=4, arg4=8):
print(arg1, arg2, arg3, arg4)
In [46]:
f1(3, 2)
3 2 4 8
In [47]:
f1(10, 20, 30, 40)
10 20 30 40
In [48]:
f1(25, 50, arg4=100)
25 50 4 100
In [49]:
f1(arg4=2, arg1=3, arg2=4)
3 4 4 2
In [50]:
f1()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[50], line 1 ----> 1 f1() TypeError: f1() missing 2 required positional arguments: 'arg1' and 'arg2'
In [52]:
f1(arg3=10, arg4=20, 30, 40)
Cell In[52], line 1 f1(arg3=10, arg4=20, 30, 40) ^ SyntaxError: positional argument follows keyword argument
In [53]:
f1(4, 5, arg2=6)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[53], line 1 ----> 1 f1(4, 5, arg2=6) TypeError: f1() got multiple values for argument 'arg2'
In [54]:
f1(4, 5, arg3=5, arg5=6)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[54], line 1 ----> 1 f1(4, 5, arg3=5, arg5=6) TypeError: f1() got an unexpected keyword argument 'arg5'
In [55]:
def f1(*x, y=20):
print(x)
print(y)
In [56]:
f1(10, 20, 30, 777)
(10, 20, 30, 40) 20
In [57]:
f1(10, 20, 30, y=777)
(10, 20, 30) 777
In [ ]:
# # Types of Variables/Variable Scopes :-¶
In [2]:
# 1. Global Variables
# 2. Local Variables
# 1. Global Variables :-¶
In [5]:
# The variables which are declared outside of the function
# Avaialable for all functions.
In [6]:
a = 10
def f1():
print(a)
def f2():
print(a)
f1()
f2()
10 10
# 2. Local Variables :-¶
In [8]:
# The variables which are declared inside of the function
# Avaialable only for that function.
In [11]:
def f1():
b = 10
print(b)
f1()
10
In [12]:
def f1():
b = 10
print(b)
def f2():
print(b)
f1()
f2()
10
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[12], line 11 7 print(b) 10 f1() ---> 11 f2() Cell In[12], line 7, in f2() 6 def f2(): ----> 7 print(b) NameError: name 'b' is not defined
In [13]:
# Gloabl ===> Global to all functions.
# Local ===> Local to a particular function.
In [1]:
a = 10 # Global variable
def f1():
a = 777 # Local variable
print(a)
def f2():
print(a)
f1()
f2()
777 10
# Global Keyword :-¶
In [9]:
# 1. To make global varaibles available to the functions so that we can perform required modifications.
In [18]:
a = 10 # Global variable
def f1():
global a # Make Global variable available to f1
a = 777
print(a)
def f2():
print(a)
f1()
f2()
777 777
In [19]:
a = 10 # Global variable
def f1():
global a = 777 # Make Global variable available to f1
print(a)
def f2():
print(a)
f1()
f2()
Cell In[19], line 5 global a = 777 # Make Global variable available to f1 ^ SyntaxError: invalid syntax
In [11]:
# 2. To declare global variables inside functions.
In [14]:
def f1():
global c # Now onwards c is global varibale but not local variable
c = 10
print(c)
def f2():
print(c)
f1()
f2()
10 10
In [16]:
def f1():
global d # Now onwards d is global varibale but not local variable
d = 10
print(d)
def f2():
print(d)
f2()
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[16], line 11 7 def f2(): 8 print(d) ---> 11 f2() Cell In[16], line 8, in f2() 7 def f2(): ----> 8 print(d) NameError: name 'd' is not defined
In [17]:
def f1():
global e # Now onwards e is global varibale but not local variable
e = 10
print(e)
def f2():
e = 777
print(e)
f1()
f2()
print(e)
10 777 10
In [22]:
f = 10
def f1():
f = 777
print(f)
f1()
print(f)
777 10
In [24]:
# How to print global varibale value inside fuction containing local variable.
# If the local and global varibale have the same name then how to differentiate values?
In [30]:
a1 = 10
def f1():
a1 = 777
print("Local Variable Value:", a1)
# How to print global variable value of 'a1'
global a1
print("Global Variable Value:", a1)
f1()
Cell In[30], line 9 global a1 ^ SyntaxError: name 'a1' is used prior to global declaration
In [31]:
a1 = 10
def f1():
a1 = 777
print("Local Variable Value:", a1)
# How to print global variable value of 'a1'
print("Global Variable Value:", globals())
f1()
Local Variable Value: 777
Global Variable Value: {'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', 'a = 10\n\n\ndef f1():\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a\n a = 777 # Local variable\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# # Global Keyword :-', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '# 2. ', '# 2. To declare global variables inside functions.', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global d # Now onwards c is global varibale but not local variable\n d = 10\n print(d)\n\n\ndef f2():\n print(d)\n\n\nf2()', 'def f1():\n global e # Now onwards e is global varibale but not local variable\n e = 10\n print(e)\n\n\ndef f2():\n e = 777\n print(e)\n\nf1()\nf2()\nprint(e)', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '# How to print global varibale value inside fuction containing local variable', '# How to print global varibale value inside fuction containing local variable.\n\n# If the local and global varibale have the same name then how to differentiate values?', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals(a1))\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()'], '_oh': {}, '_dh': [WindowsPath('c:/Users/pulki/Python/python_fundamentals')], 'In': ['', 'a = 10\n\n\ndef f1():\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a\n a = 777 # Local variable\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# # Global Keyword :-', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '# 2. ', '# 2. To declare global variables inside functions.', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global d # Now onwards c is global varibale but not local variable\n d = 10\n print(d)\n\n\ndef f2():\n print(d)\n\n\nf2()', 'def f1():\n global e # Now onwards e is global varibale but not local variable\n e = 10\n print(e)\n\n\ndef f2():\n e = 777\n print(e)\n\nf1()\nf2()\nprint(e)', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '# How to print global varibale value inside fuction containing local variable', '# How to print global varibale value inside fuction containing local variable.\n\n# If the local and global varibale have the same name then how to differentiate values?', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals(a1))\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()'], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000021A49C68B50>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000021A49C75990>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000021A49C75990>, 'open': <function open at 0x0000021A47C06AC0>, '_': '', '__': '', '___': '', '__vsc_ipynb_file__': 'c:\\Users\\pulki\\Python\\python_fundamentals\\58_Types_of_Variables.ipynb', '_i': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', '_ii': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', '_iii': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', '_i1': 'a = 10\n\n\ndef f1():\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a': 777, 'f1': <function f1 at 0x0000021A49D6A2A0>, 'f2': <function f2 at 0x0000021A4A29D620>, '_i2': 'a = 10 # Global variable\n\n\ndef f1():\n global a\n a = 777 # Local variable\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i3': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i4': '# # Global Keyword :-', '_i5': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i6': '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '_i7': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i8': 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i9': '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '_i10': '# 2. ', '_i11': '# 2. To declare global variables inside functions.', '_i12': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'c': 10, '_i13': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', '_i14': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', '_i15': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', '_i16': 'def f1():\n global d # Now onwards c is global varibale but not local variable\n d = 10\n print(d)\n\n\ndef f2():\n print(d)\n\n\nf2()', '_i17': 'def f1():\n global e # Now onwards e is global varibale but not local variable\n e = 10\n print(e)\n\n\ndef f2():\n e = 777\n print(e)\n\nf1()\nf2()\nprint(e)', 'e': 10, '_i18': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i19': 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i20': 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()', 'f': 10, '_i21': 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '_i22': 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '_i23': '# How to print global varibale value inside fuction containing local variable', '_i24': '# How to print global varibale value inside fuction containing local variable.\n\n# If the local and global varibale have the same name then how to differentiate values?', '_i25': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()\nprint(f)', 'a1': 10, '_i26': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals(a1))\n\n\nf1()\nprint(f)', '_i27': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()\nprint(f)', '_i28': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', '_i29': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', '_i30': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', '_i31': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()'}
In [33]:
a1 = 10
def f1():
a1 = 777
print("Local Variable Value:", a1)
# How to print global variable value of 'a1'
print("Global Variable Value:", globals()['a1'])
print("Global Variable Value:", globals().get('a1'))
f1()
Local Variable Value: 777 Global Variable Value: 10 Global Variable Value: 10
In [ ]:
In [2]:
a = 10
for i in range(1):
b = 20
print(a, b)
10 20
# # Recursive Functions :-¶
In [6]:
# A function that calls itself is known as Recursive Function.
# factorial(n) = n * (n-1) * (n-2) * ....1
# factorial(n) = n * factorial(n-1)
In [7]:
# 1. We can reduce the length of the code and improves readability.
# 2. We can solve very complex problems also very easily.
In [15]:
def factorial(n):
print("Finding Factorial of", n)
if n == 0:
result = 1
else:
result = n * factorial(n - 1)
print("Completion of Finding Factorial of {} and Result is {}".format(n, result))
return result
print("Factorial :", factorial(4))
Finding Factorial of 4 Finding Factorial of 3 Finding Factorial of 2 Finding Factorial of 1 Finding Factorial of 0 Completion of Finding Factorial of 0 and Result is 1 Completion of Finding Factorial of 1 and Result is 1 Completion of Finding Factorial of 2 and Result is 2 Completion of Finding Factorial of 3 and Result is 6 Completion of Finding Factorial of 4 and Result is 24 Factorial : 24
In [23]:
def fib(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
print(fib(4))
3
In [24]:
print(fib(5))
5
In [25]:
print(fib(6))
8
In [ ]:
# # Anonymous Fuctions/ Lambda Functions :-¶
In [1]:
# Nameless functions are called anonymous functions.
In [3]:
# # Normal Function :-
# By using def keyword
# function name: squareIt
In [4]:
def squareIt(n):
return n * n
# Anonymous Function :-¶
In [6]:
# We have to use lambda keyword
# lambda n : n * n
# lambda arguments_list:expression
In [9]:
s = lambda n: n * n
print("The Square is {}".format(s(4)))
The Square is 16
In [10]:
# Lambda Function to find sum of 2 given numbers?
In [12]:
s = lambda a, b: a + b
print("Sum:", s(10, 20))
Sum: 30
In [13]:
# To find biggest of 2 numbers?
In [17]:
s = lambda a, b: a if a > b else b
print("Biggest Number is", s(10, 20))
Biggest Number is 20
In [15]:
# To find biggest of 3 numbers?
In [16]:
s = lambda a, b, c: a if a > b and a > c else b if b > c else c
print("Biggest Number is", s(10, 20, 30))
Biggest Number is 30
In [18]:
# # Python Lambda functions are always single line functions only.
In [ ]:
In [1]:
# # Lmabda Functions :-
In [3]:
# We can pass a function as argument to another functions.
# In such cases Lambda functions are best choice.
# filter()
# map()
# reduce()
# 1. filter() Function :-¶
In [10]:
# To filter values based on some condition.
In [7]:
# 10 values filter top 3 values.
# 10 numbers filter only even numbers.
# input = [1, 2, 3, 4, 5, 6, 7, 8]
# [2, 4, 6, 8]
# filter(function, sequence)
In [12]:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
l = [0, 5, 10, 15, 20, 25]
output = filter(is_even, l)
print(type(output))
print(output)
<class 'filter'> <filter object at 0x0000026C05F20DF0>
In [13]:
l = [0, 5, 10, 15, 20, 25]
output = list(filter(is_even, l))
print(type(output))
print(output)
<class 'list'> [0, 10, 20]
In [1]:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
l = [0, 5, 10, 15, 20, 25]
output = []
for x in l:
if is_even(x) == True:
output.append(x)
print(type(output))
print(output)
<class 'list'> [0, 10, 20]
In [4]:
# It means filter internally looping for each value present in list.
In [6]:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
lambda n: n % 2 == 0
Out[6]:
<function __main__.<lambda>(n)>
In [7]:
l = [0, 5, 10, 15, 20, 25]
evens = list(filter(lambda n: n % 2 == 0, l))
odds = list(filter(lambda n: n % 2 != 0, l))
print(evens)
print(odds)
[0, 10, 20] [5, 15, 25]
In [8]:
t = ("A", "AA", "AAA", "AAAA", "AAAAA")
# return all strings where length is >= 3
output = list(filter(lambda s: len(s) >= 3, t))
print(output)
['AAA', 'AAAA', 'AAAAA']
In [9]:
# List of employee objects. List out all employees which can go to pub?
# his salary is > 10000 and he has gf and his age > 21
# l = [e1, e2, e3, e4]
# output = filter(lambda e:e.sal > 10000 and e.age > 21 and e.hasgf == True, l)
# 2. map() Function :-¶
In [12]:
# filter()
# input : 10 elements
# output : 10 or less
# map()
# input : 10 elements
# output : 10 elements
# For every input value, generate output value based on some operation increment 10% salary for every employee.
In [ ]:
# map(function, sequence)
In [17]:
def squarIt(n):
return n * n
l = [1, 2, 3, 4, 5]
m = map(squarIt, l)
print(type(m))
print(m)
<class 'map'> <map object at 0x00000216D4BB6530>
In [16]:
l = [1, 2, 3, 4, 5]
m = list(map(squarIt, l))
print(type(m))
print(m)
<class 'list'> [1, 4, 9, 16, 25]
In [22]:
# # without lambda function :-
def squarIt(n):
return n * n
l = [1, 2, 3, 4, 5]
m = list(map(squarIt, l))
print(type(m))
print(m)
# # with lambda function :-
l = [1, 2, 3, 4, 5]
m = list(map(lambda n: n * n, l))
print(type(m))
print(m)
<class 'list'> [1, 4, 9, 16, 25] <class 'list'> [1, 4, 9, 16, 25]
In [21]:
l = [1, 2, 3, 4, 5]
m = list(map(lambda n: 2 * n, l))
print(m)
[2, 4, 6, 8, 10]
In [ ]:
In [1]:
l = [0, 5, 10, 15, 20, 25]
# list out all odd numberws from the list
output = list(filter(lambda n: n % 2 != 0, l))
print(output)
[5, 15, 25]
In [2]:
# list out all numbers which are divisible by 3
output = list(filter(lambda n: n % 3 == 0, l))
print(output)
[0, 15]
In [3]:
# list = [0, 5, 10, 15, 20, 25]
# # list out all odd numberws from the list
# output = list(filter(lambda n: n % 2 != 0, list))
# print(output)
# # TypeError Traceback (most recent call last)
# # Cell In[3], line 5
# # 1 list = [0, 5, 10, 15, 20, 25]
# # 3 # list out all odd numberws from the list
# # ----> 5 output = list(filter(lambda n: n % 2 != 0, list))
# # 6 print(output)
# # TypeError: 'list' object is not callable
In [5]:
list1 = [0, 5, 10, 15, 20, 25]
# list out all odd numberws from the list
output = list(filter(lambda n: n % 2 != 0, list1))
print(output)
[5, 15, 25]
In [7]:
# create a new list with double of values present in list1
output = list(map(lambda n: 2 * n, list1))
print(output)
[0, 10, 20, 30, 40, 50]
In [9]:
# create a new list with numbers which are divisible by 3
output = list(map(lambda n: n % 3 == 0, list1))
print(output)
[True, False, False, True, False, False]
In [10]:
# input : 10 values
# output :
# filter() ---> 10 or less
# map() ---> 10
In [11]:
# map(function, list)
# We can use map function on multiple list also
In [12]:
l1 = [1, 2, 3, 4]
l2 = [10, 20, 30, 40]
# Generate output by multiplying values from both lists
output = list(map(lambda x, y: x * y, l1, l2))
print(output)
[10, 40, 90, 160]
In [13]:
l1 = [1, 2, 3, 4, 5]
l2 = [10, 20, 30, 40, 50, 60, 70]
# Generate output by multiplying values from both lists
output = list(map(lambda x, y: x * y, l1, l2))
print(output)
[10, 40, 90, 160, 250]
# 3. reduce() Function :-¶
In [16]:
# reduce(function, sequence)
In [15]:
# input : 10 values
# output :
# filter() ---> 10 or less
# map() ---> 10
# reduce() ---> 1
In [18]:
l = [10, 20, 30, 40, 50]
result = reduce(lambda x, y: x + y, l)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[18], line 3 1 l = [10, 20, 30, 40, 50] ----> 3 result = reduce(lambda x,y:x+y,) NameError: name 'reduce' is not defined
In [19]:
from functools import *
In [21]:
l = [10, 20, 30, 40, 50]
result = reduce(lambda x, y: x + y, l)
print(result)
150
In [24]:
# print the sum of numbers from 1 to 100
result = reduce(lambda x, y: x + y, range(1, 101))
print(result)
5050
In [25]:
result = reduce(lambda x, y: x * y, range(1, 4))
print(result)
6
In [26]:
def multiply(x, y):
return x * y
result = reduce(multiply, range(1, 4))
print(result)
6
In [27]:
# In the above example we have not pass the parameter to multiply then how it is working?
# We are not calling multiple fucntion. reduce() function is calling internally.
In [ ]:
# # Modules :-¶
In [2]:
# A group of functions, variables and classes saved to a file, which is nothing but module.
# Every Python file (.py file) is a module.
# Advantages of Module :-
# 1. Code Reusability
# 2. Readability
# 3. Maintainability
# 4. Development Time
# 5. Cost of Project
In [7]:
x = 888
name = "DURGASOFT"
def add(a, b):
print("SUM : ", a + b)
def product(a, b):
print("PRODUCT : ", a * b)
# Save by file name durgamath.py
In [8]:
# import modulename
# modulename.varaiblename
# modulename.functionname()
In [9]:
import durgamath
print(durgamath.x)
print(durgamath.name)
888 DURGASOFT
In [11]:
durgamath.add(10, 20)
SUM : 30
In [12]:
durgamath.product(10, 20)
PRODUCT : 200
In [14]:
# .pyc file will be generated for modules in __pycache__ which we wrote when we call them or when we use.
# .pyc file will be not generated for normal .py file unless we use it as a module.
In [ ]:
# Module Name Aliasing :-¶
In [5]:
import durgamath as dm
print(dm.x)
print(dm.name)
dm.add(10, 20)
dm.product(10, 20)
888 DURGASOFT SUM : 30 PRODUCT : 200
In [6]:
# Once we define alias name, we cannot use original name.
# from import :-¶
In [11]:
# Usually we can acces members of a module by using module name.
# If we don't want to use module name then we should go for from import.
# We can access members directly.
In [12]:
from durgamath import x, name
print(x)
print(name)
888 DURGASOFT
In [13]:
add(10,20)
SUM : 30
In [16]:
from durgamath import * # to import everything from file
print(dm.x)
print(dm.name)
dm.add(10, 20)
dm.product(10, 20)
888 DURGASOFT SUM : 30 PRODUCT : 200
In [17]:
# We can write import statement anywhere in the code it is not compulsory to add import as 1st statement.
# Member Aliasing :-¶
In [20]:
from durgamath import add as a, product as b, name as n
print(n)
a(10, 20)
b(10, 20)
DURGASOFT SUM : 30 PRODUCT : 200
In [21]:
a(10, 20, 30)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[21], line 1 ----> 1 a(10, 20, 30) TypeError: add() takes 2 positional arguments but 3 were given
In [24]:
# from durgamath as dm import add as a, product as p
# is this right?
# No, it is not correct.
# Various Possibilities of import :-¶
In [26]:
# import module1
# import module1, module2, module3
# import module1 as m1
# import module1 as m1, module2 as m2, module3 as m3
# from module1 import member1
# from module1 import member1, member2, member3
# from module import *
# from module import member1 as m1
# from module import member1 as m1, member2 as m2
# from module1, module2 import * ===> Invalid
# Module Naming Conflicts :-¶
In [29]:
from module1 import *
add(10, 20)
module1 add function SUM: 30
In [30]:
from module2 import *
add(10, 20)
module2 add function SUM: 30
In [31]:
from module1 import *
from module2 import *
add(10, 20)
module2 add function SUM: 30
In [33]:
from module1 import *
from module2 import *
def add(a, b):
print("Current Module Add Function")
print("SUM:", a + b)
add(10, 20)
Current Module Add Function SUM: 30
In [34]:
from module1 import *
def add(a, b):
print("Current Module Add Function")
print("SUM:", a + b)
from module2 import *
add(10, 20)
module2 add function SUM: 30
In [37]:
# In the case of conflicts, python will always consider the most recent copy.
x = 10
print(x)
x = 20
print(x)
x = 30
print(x)
10 20 30
In [39]:
# The most recent copy ---> order wise which is avaialable at last.
In [40]:
# How to call module1 add function?
# Two Ways :-¶
In [44]:
# 1st way :-
In [41]:
import module1
import module2
module1.add(10, 20)
module2.add(10, 20)
module1 add function SUM: 30 module2 add function SUM: 30
In [46]:
# 2nd way :-
In [42]:
from module1 import add as m1
from module2 import add as m2
m1.add(10, 20)
m2.add(10, 20)
module1 add function SUM: 30 module2 add function SUM: 30
# # Reloading of Module :-¶
In [48]:
# import module will be loading only once in PVM whether you call it in multiple files multiple times.
# By default module will be loaded only once eventhough we are importing multiple times.
In [49]:
# Advantage :-
# Performance is more
# Problem :-
# We are missing updations of that module.
In [50]:
import module1
module1.add(10, 20)
module1 add function SUM: 30
In [51]:
import module1
module1.add(10, 20)
module1 add function SUM: 30
In [52]:
import time
import module1
module1.add(10, 20)
print("Progrsam Entering into Sleeping State")
time.sleep(45)
print("Just Wake up and calling Updated Fuction")
import module1
module1.product(10, 20)
module1 add function SUM: 30 Progrsam Entering into Sleeping State Just Wake up and calling Updated Fuction
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[52], line 10 7 print("Just Wake up and calling Updated Fuction") 8 import module1 ---> 10 module1.product(10, 20) AttributeError: module 'module1' has no attribute 'product'
In [ ]:
# reload()
# imp module
In [53]:
import time
import imp
import module1
module1.add(10, 20)
print("Progrsam Entering into Sleeping State")
time.sleep(45)
print("Just Wake up and calling Updated Fuction")
imp.reload(module1)
module1.product(10, 20)
C:\Users\pulki\AppData\Local\Temp\ipykernel_7632\3697301949.py:2: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import imp
module1 add function SUM: 30 Progrsam Entering into Sleeping State Just Wake up and calling Updated Fuction PRODUCT : 200
In [54]:
# My Python Program keep on printing share price values.
# Some module is available to provide shares data.
In [ ]:
# Without Reloading program if we run program second time updation is occur?
# PVM will be stopped
# PVM will be started again
# dir() and help() functions :-¶
# Finding Members of Module by using dir() function :-¶
In [2]:
# Just To list out members of a module
# dir() ---> To listout members of current module
# dir(module_name) ---> To listout members of specified module
In [3]:
a = 10
b = 20
def add(a, b):
return a + b
def product(a, b):
return a * b
# To listout all members of current module
print(dir())
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '__vsc_ipynb_file__', '_dh', '_i', '_i1', '_i2', '_i3', '_ih', '_ii', '_iii', '_oh', 'a', 'add', 'b', 'exit', 'get_ipython', 'module1', 'open', 'product', 'quit']
In [4]:
# For every module, PVM will add several predefined variables, which are internally used by PVM. Even these varaibles can be used by programmer based on his requirement.
In [5]:
# To list out all members of math module
import math
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
# Help documentation of a Module :-¶
In [6]:
# help()
In [7]:
import math
help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
cbrt(x, /)
Return the cube root of x.
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n.
Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0.
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
dist(p, q, /)
Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.
Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
exp2(x, /)
Return 2 raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(n, /)
Find n!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> value
Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y).
For example, the hypotenuse of a 3/4/5 right triangle is:
>>> hypot(3.0, 4.0)
5.0
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /)
Return the integer part of the square root of the input.
lcm(*integers)
Least Common Multiple.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
nextafter(x, y, /)
Return the next floating-point value after x towards y.
perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order.
Evaluates to n! / (n - k)! when k <= n and evaluates
to zero when k > n.
If k is not specified or is None, then k defaults to n
and the function returns n!.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
pow(x, y, /)
Return x**y (x to the power of y).
prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method.
ulp(x, /)
Return the value of the least significant bit of the float x.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
(built-in)
In [8]:
import random
help(random)
Help on module random:
NAME
random - Random variable generators.
MODULE REFERENCE
https://docs.python.org/3.11/library/random.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
distributions on the real line:
------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull
distributions on the circle (angles 0 to 2pi)
---------------------------------------------
circular uniform
von Mises
General notes on the underlying Mersenne Twister core generator:
* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.
CLASSES
_random.Random(builtins.object)
Random
SystemRandom
class Random(_random.Random)
| Random(x=None)
|
| Random number generator base class used by bound module functions.
|
| Used to instantiate instances of Random to get generators that don't
| share state.
|
| Class Random can also be subclassed if you want to use a different basic
| generator of your own devising: in that case, override the following
| methods: random(), seed(), getstate(), and setstate().
| Optionally, implement a getrandbits() method so that randrange()
| can cover arbitrarily large ranges.
|
| Method resolution order:
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu=0.0, sigma=1.0)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| getstate(self)
| Return internal state; can be passed to setstate() later.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu=0.0, sigma=1.0)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randbytes(self, n)
| Generate n random bytes.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(stop) or range(start, stop[, step]).
|
| Roughly equivalent to ``choice(range(start, stop, step))`` but
| supports arbitrarily large ranges and is optimized for common cases.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| seed(self, a=None, version=2)
| Initialize internal state from a seed.
|
| The only supported seed types are None, int, float,
| str, bytes, and bytearray.
|
| None or no argument seeds from current time or from an operating
| system specific randomness source if available.
|
| If *a* is an int, all bits are used.
|
| For version 2 (the default), all of the bits are used if *a* is a str,
| bytes, or bytearray. For version 1 (provided for reproducing random
| sequences from older versions of Python), the algorithm for str and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x)
| Shuffle list x in place, and return None.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __init_subclass__(**kwargs)
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Methods inherited from _random.Random:
|
| getrandbits(self, k, /)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| random(self, /)
| random() -> x in the interval [0, 1).
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) class method of _random.Random
| Create and return a new object. See help(type) for accurate signature.
class SystemRandom(Random)
| SystemRandom(x=None)
|
| Alternate random number generator using sources provided
| by the operating system (such as /dev/urandom on Unix or
| CryptGenRandom on Windows).
|
| Not available on all systems (see os.urandom() for details).
|
| Method resolution order:
| SystemRandom
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| randbytes(self, n)
| Generate n random bytes.
|
| random(self)
| Get the next random number in the range 0.0 <= X < 1.0.
|
| seed(self, *args, **kwds)
| Stub method. Not used for a system random number generator.
|
| setstate = _notimplemented(self, *args, **kwds)
|
| ----------------------------------------------------------------------
| Methods inherited from Random:
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu=0.0, sigma=1.0)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu=0.0, sigma=1.0)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(stop) or range(start, stop[, step]).
|
| Roughly equivalent to ``choice(range(start, stop, step))`` but
| supports arbitrarily large ranges and is optimized for common cases.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| shuffle(self, x)
| Shuffle list x in place, and return None.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods inherited from Random:
|
| __init_subclass__(**kwargs)
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Random:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) class method of _random.Random
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
betavariate(alpha, beta) method of Random instance
Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
choice(seq) method of Random instance
Choose a random element from a non-empty sequence.
choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance
Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
expovariate(lambd) method of Random instance
Exponential distribution.
lambd is 1.0 divided by the desired mean. It should be
nonzero. (The parameter would be called "lambda", but that is
a reserved word in Python.) Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.
gammavariate(alpha, beta) method of Random instance
Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
gauss(mu=0.0, sigma=1.0) method of Random instance
Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
getrandbits(k, /) method of Random instance
getrandbits(k) -> x. Generates an int with k random bits.
getstate() method of Random instance
Return internal state; can be passed to setstate() later.
lognormvariate(mu, sigma) method of Random instance
Log normal distribution.
If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.
normalvariate(mu=0.0, sigma=1.0) method of Random instance
Normal distribution.
mu is the mean, and sigma is the standard deviation.
paretovariate(alpha) method of Random instance
Pareto distribution. alpha is the shape parameter.
randbytes(n) method of Random instance
Generate n random bytes.
randint(a, b) method of Random instance
Return random integer in range [a, b], including both end points.
random() method of Random instance
random() -> x in the interval [0, 1).
randrange(start, stop=None, step=1) method of Random instance
Choose a random item from range(stop) or range(start, stop[, step]).
Roughly equivalent to ``choice(range(start, stop, step))`` but
supports arbitrarily large ranges and is optimized for common cases.
sample(population, k, *, counts=None) method of Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
Repeated elements can be specified one at a time or with the optional
counts parameter. For example:
sample(['red', 'blue'], counts=[4, 2], k=5)
is equivalent to:
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
To choose a sample from a range of integers, use range() for the
population argument. This is especially fast and space efficient
for sampling from a large population:
sample(range(10000000), 60)
seed(a=None, version=2) method of Random instance
Initialize internal state from a seed.
The only supported seed types are None, int, float,
str, bytes, and bytearray.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If *a* is an int, all bits are used.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
setstate(state) method of Random instance
Restore internal state from object returned by getstate().
shuffle(x) method of Random instance
Shuffle list x in place, and return None.
triangular(low=0.0, high=1.0, mode=None) method of Random instance
Triangular distribution.
Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution
uniform(a, b) method of Random instance
Get a random number in the range [a, b) or [a, b] depending on rounding.
vonmisesvariate(mu, kappa) method of Random instance
Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
weibullvariate(alpha, beta) method of Random instance
Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.
DATA
__all__ = ['Random', 'SystemRandom', 'betavariate', 'choice', 'choices...
FILE
c:\users\pulki\anaconda3\envs\personal\lib\random.py
In [9]:
# help() will give detailed information.
# dir() will just list members of a module.
# Extra Members added by PVM for every Module :-¶
In [10]:
# For every module, PVM will add several prdefined variabled, which are internally used by PVM. Even these variables can be used by programmer based on his requirement.
# __doc__
# __file__
# __name__
# __loader__
# __package__
In [11]:
print(dir())
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '__vsc_ipynb_file__', '_dh', '_i', '_i1', '_i10', '_i11', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'add', 'b', 'exit', 'get_ipython', 'math', 'module1', 'open', 'product', 'quit', 'random']
In [12]:
print(__loader__)
None
In [13]:
print(__builtins__)
<module 'builtins' (built-in)>
In [14]:
print(__builtin__)
<module 'builtins' (built-in)>
In [15]:
print(__doc__)
Automatically created module for IPython interactive environment
In [16]:
print(__package__)
None
In [17]:
print(__vsc_ipynb_file__)
c:\Users\pulki\Python\python_fundamentals\65_Finding_Members_of_Modules.ipynb
In [18]:
# # __doc__ :-
In [19]:
# This variable holds documentation string.
In [20]:
""" This code is written by Pulkit Chahal """
print(__doc__)
This code is written by Pulkit Chahal
In [21]:
""" This code is written by Pulkit Chahal """
""" This code is written by Chahal """
""" This code is written by Pulkit """
print(__doc__)
This code is written by Pulkit
In [22]:
import math
print(math.__doc__)
This module provides access to the mathematical functions defined by the C standard.
In [23]:
import random
print(random.__doc__)
Random variable generators.
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
distributions on the real line:
------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull
distributions on the circle (angles 0 to 2pi)
---------------------------------------------
circular uniform
von Mises
General notes on the underlying Mersenne Twister core generator:
* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.
In [24]:
# # __file__ :-
In [25]:
# To get the location of file.
In [26]:
print("File Name:", __file__)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[26], line 1 ----> 1 print("File Name:", __file__) NameError: name '__file__' is not defined
In [49]:
import os
print("Absolute Path:", os.path.abspath(__vsc_ipynb_file__))
Absolute Path: c:\Users\pulki\Python\python_fundamentals\65_Finding_Members_of_Modules.ipynb
In [27]:
print("Directory:", os.path.dirname(os.path.abspath(__vsc_ipynb_file__)))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[27], line 1 ----> 1 print("Directory:", os.path.dirname(os.path.abspath(__vsc_ipynb_file__))) NameError: name 'os' is not defined
In [28]:
# # __name__ :-
In [29]:
# py module1.py ===> Direct execution of module1.py
# py test.py ===> Indirect execution of module1.py
In [30]:
print(__name__)
__main__
In [31]:
import module1
print("test module")
test module
In [32]:
# Module1 file
print("Module1 Execution")
Module1 Execution
In [33]:
# __name__ ---> Magic Variable
# __name__
# ===> Direct Execution : __main__
# It means we are executing module1 as main program.
# ===> Indirect Execution : modulename (module1)
In [34]:
# __name__ ===> __main__ (DE)
# ===> module1 (IE)
In [35]:
if __name__ == '___main__':
print('Executing Directly')
else:
print('Executing Indiretly because of import statement')
Executing Indiretly because of import statement
In [36]:
# Module1 file
def f1():
print("f1 function")
def f2():
print("f2 function")
def f3():
print("f3 function")
def f4():
print("f4 function")
f1()
f2()
f3()
f4()
f1 function f2 function f3 function f4 function
In [37]:
import module1
print("We required only some functions but not all")
module1.f1()
We required only some functions but not all f1 function
In [ ]:
# # Working with Random Module :-¶
In [2]:
# Random module contains several functions to generate random numbers.
# Developing Games
# Cryptography
# OTP
# Random password
In [3]:
# 1. random()
# 2. uniform()
# 3. randint()
# 4. randrange()
# 5. choice()
# 1. random() :-¶
In [6]:
# generate some float values between 0 and 1 (not inclusive)
# 0.9999345
# 0.1234878
In [21]:
from random import *
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
0.6464542100401829 0.010675848165000446 0.626119271169842 0.9968781442082784 0.008614968664742984 0.589771783023502 0.409783533525354 0.8431020634036197 0.48870048075470374 0.3819780839674809 0.12230734210818128
# 2. uniform() :-¶
In [13]:
# To generate random float vlaue between 2 given numbers (not inclusive)
# uniform(1,10)
In [17]:
from random import *
for i in range(10):
print(uniform(1, 10))
3.1347665605027677 6.814167460300179 9.507224080637071 7.45048372921796 1.670982266184999 5.7269930756381235 2.172093103180653 2.317205953537269 4.6647954685826205 5.140179460010281
# 3. randint() :-¶
In [22]:
# To generate a random interger between 2 given numbers (inclusive)
# randint(1, 10) ---> 1 to 10 including 1 and 10
In [28]:
from random import *
for i in range(10):
print(randint(1, 10))
1 5 8 7 7 5 1 10 5 3
# 4. randrange([begin], end, [step]) :-¶
In [31]:
# Returns a random number from range
# begin <= x < end
# begin is optional and default value is 0.
# step is optional and default value is 1.
# randrane(10) ---> generates a random number from 0 to 9
# randrange(1, 10) ---> generates a random number from 1 to 10
# randrange(1, 11, 2) ---> generates a random number from 1 to 10 by increment of 2
# [1, 3, 5, 7, 9]
# randrange(0, 11, 2) ---> generates a random number from 0 to 10 by increment of 2
# [0, 2, 4, 6, 8]
In [32]:
from random import *
for i in range(10):
print(randrange(10))
8 1 1 5 5 9 6 7 4 6
In [33]:
from random import *
for i in range(10):
print(randrange(1, 11))
4 3 2 4 5 7 6 8 3 2
In [34]:
from random import *
for i in range(10):
print(randrange(1, 11, 2))
5 3 3 1 3 3 5 3 7 5
In [37]:
from random import *
for i in range(10):
print(randrange(0, 11, 2))
2 2 10 0 0 6 10 0 6 8
# 5. choice() :-¶
In [41]:
# It won't generate random number.
# It will generate a random object from the given sequence.
In [44]:
from random import *
l = ["Sunny", "Bunny", "Chinny", "Vinny", "Pinny"]
for i in range(10):
print(choice(l))
Vinny Chinny Pinny Bunny Chinny Pinny Sunny Pinny Pinny Sunny
In [47]:
from random import *
alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(10):
print(choice(alphabets))
S W W K Y G n y a B
In [48]:
# 1. To genrate 6-digit random number which can be used as OTP?
In [55]:
from random import *
print(
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
)
5 4 0 4 5 3
In [56]:
from random import *
print(
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
sep="",
)
092666
In [57]:
from random import *
for i in range(10):
print(
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
sep="",
)
239368 411586 955018 891601 161595 783737 720103 579960 681697 663860
In [59]:
# 2. Random pwd of 6 length?
# where 1, 3, 5 are alphabet symbols
# 2, 4, 6 are digits
In [61]:
from random import *
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
for i in range(10):
print(
choice(alphabets)
+ choice(digits)
+ choice(alphabets)
+ choice(digits)
+ choice(alphabets)
+ choice(digits)
)
B2E3X5 H2H4F1 T1Y7F0 V0M0H4 G1G4E6 V4A5S8 P7J2S1 W0T9N3 L7B5X5 O1U3M0
In [ ]:
In [20]:
from random import *
alphabets = "abcdefghijklmnopqrstuvwxyz"
digits = "0123456789"
cities = ["Hyderabad", "Chennai", "Banglore", "Pune", "Delhi", "Mumbai"]
designations = [
"Software Engineer",
"Senior Software Engineer",
"Team Lead",
"Project Manager",
"Project Lead",
]
def get_fake_name():
name = choice(alphabets).upper()
n = randint(2, 6)
for i in range(n):
name = name + choice(alphabets)
return name
def get_fake_eno():
eno = "e-"
for i in range(4):
eno = eno + str(randint(0, 9))
return eno
def get_fake_salary():
esal = uniform(10000, 50000)
return esal
def get_fake_city():
city = choice(cities)
return city
def get_fake_mno():
mno = choice("6789")
for i in range(9):
mno = mno + choice(digits)
return mno
def get_fake_designation():
designation = choice(designations)
return designation
def get_fake_emp_data():
print("Employee Name :", get_fake_name())
print("Employee Number :", get_fake_eno())
print("Employee Salary : {:.2f}".format(get_fake_salary()))
print("Employee City :", get_fake_city())
print("Employee Mobile Number :", get_fake_mno())
print("Employee Designation :", get_fake_designation())
get_fake_emp_data()
Employee Name : Wefp Employee Number : e-0714 Employee Salary : 26959.20 Employee City : Mumbai Employee Mobile Number : 7147705020 Employee Designation : Project Lead
In [22]:
for i in range(3):
get_fake_emp_data()
Employee Name : Blysth Employee Number : e-8084 Employee Salary : 18230.72 Employee City : Banglore Employee Mobile Number : 7672497334 Employee Designation : Project Lead Employee Name : Cdxvdsr Employee Number : e-8162 Employee Salary : 10383.68 Employee City : Pune Employee Mobile Number : 8985711489 Employee Designation : Project Lead Employee Name : Axaz Employee Number : e-1870 Employee Salary : 16295.46 Employee City : Delhi Employee Mobile Number : 6993463914 Employee Designation : Team Lead
In [ ]:
# # Working with Math Module :-¶
In [2]:
# Math module defines several functions which can be used for mathematical operations.
# sqrt(x)
# ceil(x)
# floor(x)
# fabs(x)
# log(x)
# sin(x)
# tan(x)
In [4]:
from math import *
print(sqrt(4))
2.0
In [5]:
print(ceil(10.1))
11
In [6]:
print(ceil(10.5))
11
In [7]:
print(floor(10.1))
10
In [8]:
print(floor(10.4))
10
In [9]:
print(floor(10.5))
10
In [10]:
print(floor(10.6))
10
In [11]:
print(fabs(10.6))
10.6
In [12]:
print(fabs(-10.6))
10.6
In [13]:
import math
help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
cbrt(x, /)
Return the cube root of x.
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n.
Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0.
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
dist(p, q, /)
Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.
Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
exp2(x, /)
Return 2 raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(n, /)
Find n!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> value
Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y).
For example, the hypotenuse of a 3/4/5 right triangle is:
>>> hypot(3.0, 4.0)
5.0
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /)
Return the integer part of the square root of the input.
lcm(*integers)
Least Common Multiple.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
nextafter(x, y, /)
Return the next floating-point value after x towards y.
perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order.
Evaluates to n! / (n - k)! when k <= n and evaluates
to zero when k > n.
If k is not specified or is None, then k defaults to n
and the function returns n!.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
pow(x, y, /)
Return x**y (x to the power of y).
prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method.
ulp(x, /)
Return the value of the least significant bit of the float x.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
(built-in)
In [14]:
a = -12.99
print(floor(fabs(a)))
12
In [15]:
a = -12.99
print(fabs(floor(a)))
13.0
In [16]:
import math
l = [str(round(math.pi)) for i in range(1, 6)]
print(l)
['3', '3', '3', '3', '3']
In [17]:
round(3.4)
Out[17]:
3
In [20]:
round(3.5)
Out[20]:
4
In [19]:
round(3.6)
Out[19]:
4
In [1]:
# Modules :-
# random
# selenium
# faker
# math
# os
# re
In [ ]:
In [1]:
# Functions :-
# A group of repeatedly required lines
# Code Reusability
# Modules :-
# Python File
# A group of functions, varibales, classes saved to a file
# # Packages :-¶
In [3]:
# Basic Java Package
# core java + advanced java + oracle
# Complete Python Package
# Core Python + Advanced Python + UI + Django + Django Rest Framework + Microsoft Certification
# Complete Body Checkup Package
# Hear Checkup Package
# South India Tour Package
# 10 places
In [4]:
# A collection of python lines into a single unit ---> Function
# A collection of python functions, variable and classes into a single file ---> Module
# A collection of related modules into a folder ---> Package
In [7]:
# A collection of related modules into a single unit is nothing but package.
# Package is an encapsulation mechansim to group related modules into a single unit.
# Package is simply a folder or directory.
# If folder contains __init__.py file is considered as python package.
# A python package can contains sub package also but all packages should contain __init__.py file.
# From Python 3.3 version onwards, it is not mandatory to have __init__.py file.
In [8]:
# Advantages of Packages :-
# 1. We can resolve naming conflicts.
# 2. We can identify our components uniquely.
# 3. It imporoves modularity of the application.
# 4. It improves readability and maintainability of the applications.
In [ ]:
In [4]:
# C:\Python
# |-test.py
# |-com
# |-__init__.py
# |-module1.py (contains f1 function)
# |-durgasoft
# |-__init__.py
# |-module2.py (contains f2 function)
In [5]:
# from com.module1 import f1
# f1()
In [6]:
# from com.durgasoft.module2 import f2
# f2()
# Importance of init.py File :-¶
In [15]:
# At the time of using a package, if we want to perform any initialization activites automatically then we have to go for __init__.py
In [12]:
# but if we write print statement in noraml module also it will be executed?
# but we have to call the function in which print statement while in __init__.py it will be executed automatically.
In [14]:
# If we have __init__.py file in folder and subfolder then.
# when we call folder then only folder __init__.py will execute
# ex. from com.module import f1
# in this only folder __init__.py file will execute automatically
# when we call sub-folder then folder and sub-folder __init__.py will execute
# ex. from com.durgasoft.module2 import f1
# in this folder and sub-folder __init__.py file will execute automatically
# Need of Installing a Package :-¶
In [18]:
# If we wnat to use a package, compulsory it should be available in the current working directory.
# To make package available through out our system then we have to install that package. Once we installed we can access that package from anywhere in our system.
In [19]:
# exec('function_name')
In [ ]:
# How to Install Package :-¶
In [2]:
# from setuptools import setup
# setup(name="patterns", version="1.0", packages=["patterns"])
In [3]:
# pip is a python package management system to install and manage software packages written in python.
In [5]:
# pip install .
In [7]:
# # Alternative Way :-
# from setuptools import setup, find_packages
# setup(name="patterns", version="1.0", packages=find_packages())
In [8]:
# pip uninstall patterns
In [10]:
# pip install django (installing django library)
# pip install pymysql
# pip install selenium (for automation)
In [11]:
# pip ---> python package management software system
# npm ---> javascript
# apt ---> Ubuntu
# yum ---> redhat linux
# # Library vs Package vs Module vs Function :-¶
In [14]:
# Function ---> A group of repeatedly required lines of code.
# Module ---> A group of repeatedly required functions, variables, classes saved to a file.
# Package ---> A group of related modules into a single folder. It contains sub packages.
# Library ---> A group of packages.
In [ ]:
# # File Handling :-¶
In [2]:
# We required to store data
# student marks
# customers account information
# billing information
In [5]:
# Files are very common permanent storage areas to store our data.
# list, tuple, set, dict ===> available as long as program is in running. Once program completes these objects will be destroyed automatically and hence the data will be gone. Temporary storage areas.
In [4]:
d = {}
for i in range(3):
name = input("Enter Name :")
balance = int(input("Enter Balance :"))
d[name] = balance
print(d)
{'asdbj': 45, 'dsafda': 2452, 'asdfas4': 24}
In [6]:
# Permanent Storage Areas :-
# files
# database
# big data technologies/cloud
# Types of Files :-¶
In [9]:
# 2 Types of Files :-
# 1. text files :
# abc.txt, test.py
# 2. Binary Files:
# images, video files, audio files etc
# Opening of a File :-¶
In [13]:
# f = open(filename, mode)
# Example :-
f = open("abc.txt", "r")
data = f.read()
print(data)
This is Python Practice
In [15]:
# # The allowed modes are:
# r, w, a, r+, w+, a+, x
# 1. r :-¶
In [27]:
# Open an existing file for read operation. The file pointer is at begining of the file.
# FileNotFoundError
# default mode is red mode
# 2. w :-¶
In [29]:
# Open an existing file for write operation.
# Overwrite of existing data will be happened.
# If the specified file not already availabel, then this mode will create that file.
In [20]:
f = open('abc.txt', 'w')
# 3. a :-¶
In [31]:
# Open an existing file for append operation.
# It won't overwrite of existing data will be happened.
# If the specified file not already availabel, then this mode will create that file.
# 4. r+ :-¶
In [32]:
# To read and write data.
# The previous data won't be overwritten.
# 5. w+ :-¶
In [35]:
# To write and read data.
# It will overwrite existing data.
# 6. a+ :-¶
In [37]:
# It append and read.
# It won't overwrite existing data.
# 7. x :-¶
In [39]:
# To open a file in exclusive createion mode.
# Specified file should not be avaialable already, otherwise we will get FileExistsError
# # 2. Binary File :-¶
In [41]:
# rb
# wb
# ab
# r+b
# w+b
# a+b
# xb
# Closing of a File :-¶
In [43]:
f.close()
# Various Properties of File Object :-¶
In [46]:
f = open("abc.txt", "r")
In [47]:
# f.name ---> Name of opened File
# f.module ---> Mode in which we opened that file.
# f.closed ---> Is the file closed (True/False)
# f.readable() ---> Returns True if the file is readable
# f.wrtable() ---> Returns True if the file is writable
In [51]:
f = open("abc.txt", "r")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : r Is File Readable : True Is File Writable : False Is File Closed : False Is File Closed : True
In [1]:
f = open("abc.txt", "w")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : w Is File Readable : False Is File Writable : True Is File Closed : False Is File Closed : True
In [2]:
f = open("abc.txt", "r+")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : r+ Is File Readable : True Is File Writable : True Is File Closed : False Is File Closed : True
In [3]:
f = open("abc.txt", "w+")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : w+ Is File Readable : True Is File Writable : True Is File Closed : False Is File Closed : True
In [4]:
f = open("abc.txt", "a")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : a Is File Readable : False Is File Writable : True Is File Closed : False Is File Closed : True
In [ ]:
# Write Data to the text Files :-¶
In [2]:
# 2 METHODS :-
# f.write(str)
# f.writelines(list of lines)
In [6]:
f = open("abc.txt", "w")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [14]:
f = open("abc.txt", "w+")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [13]:
f = open("abc.txt", "r+")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [12]:
# Data will be written in existing file without resenting file
f = open("abc.txt", "a+")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [15]:
# Data will be written in existing file without resenting file
f = open("abc.txt", "a")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [18]:
f = open("abc.txt", "x")
f.write("Durga ")
f.write("Software ")
f.write("Solutions ")
print("Data Written to the File Successfully")
f.close()
--------------------------------------------------------------------------- FileExistsError Traceback (most recent call last) Cell In[18], line 1 ----> 1 f = open("abc.txt", "x") 3 f.write("Durga ") 4 f.write("Software ") File c:\Users\pulki\anaconda3\envs\Personal\Lib\site-packages\IPython\core\interactiveshell.py:324, in _modified_open(file, *args, **kwargs) 317 if file in {0, 1, 2}: 318 raise ValueError( 319 f"IPython won't let you open fd={file} by default " 320 "as it is likely to crash IPython. If you know what you are doing, " 321 "you can use builtins' open." 322 ) --> 324 return io_open(file, *args, **kwargs) FileExistsError: [Errno 17] File exists: 'abc.txt'
In [19]:
# f.writelines(list of lines) :-
In [20]:
f = open("abc.txt", "w")
l = ["Bunny", "Chinny", "Sunny", "Pinny", "Vinny"]
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [21]:
f = open("abc.txt", "w")
l = ["Bunny\n", "Chinny\n", "Sunny\n", "Pinny\n", "Vinny\n"]
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [22]:
# write(str)
# multiple strings ---> multiple write() methods
# writelines(list|ste|tuple|dict)
In [24]:
f = open("abc.txt", "w")
l = ("Bunny\n", "Chinny\n", "Sunny\n", "Pinny\n", "Vinny")
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [26]:
f = open("abc.txt", "w")
l = {"Bunny\n", "Chinny\n", "Sunny\n", "Pinny\n", "Vinny"}
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
# for set order wise no guaranttee
Data Written to the File Successfully
In [27]:
f = open("abc.txt", "w")
l = {"A": 100, "B": 200, "C": 300}
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [28]:
f = open("abc.txt", "w")
l = {100: "A", 200: "B", 300: "C"}
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[28], line 4 1 f = open("abc.txt", "w") 2 l = {100: "A", 200: "B", 300: "C"} ----> 4 f.writelines(l) 6 print("Data Written to the File Successfully") 7 f.close() TypeError: write() argument must be str, not int
In [30]:
f = open("C:\\GNA\\abc.txt", "w")
f.write("First Line\n")
f.write("Second Line\n")
f.write("Third Line\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [33]:
fname = input("Enter File Name:")
f = open("C:\\GNA\\" + fname + ".txt", "w")
while True:
data = input("Enter Data to Write:")
f.write(data + "\n")
option = input("Do you want to add some more data[Yes|No]:")
if option.lower() == "no":
break
print("Your Provided Data Written to the File Successfully")
f = open("C:\\GNA\\" + fname + ".txt", "r")
print(f.read())
f.close()
Your Provided Data Written to the File Successfully durga software solutions
# Reading Data from Files :-¶
In [35]:
# read() ---> To read total data from the file
# read(n) ---> To read n characters from the file
# readline() ---> To read only one line
# readlines() ---> To read all lines into a list
In [36]:
f = open("abc.txt", "r")
data = f.read()
print(data)
Sunny Bunny Chinny Vinny Pinny Munny
In [39]:
f = open("abc.txt", "r")
data = f.read(10)
print(data)
Sunny Bunn
In [40]:
f = open("abc.txt", "r")
data = f.readline()
print(data)
Sunny
In [47]:
f = open("abc.txt", "r")
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
Sunny Bunny Chinny Vinny Pinny Munny
In [48]:
data = f.readline()
print(data)
data = f.readline()
print(data)
In [51]:
# After lines are finished while using f.readline() then it will keep on reading/printing empty lines.
# f.readline() will automatically add new empty line after each new line.
In [46]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
['Sunny\n', 'Bunny\n', 'Chinny\n', 'Vinny\n', 'Pinny\n', 'Munny']
In [ ]:
In [11]:
f = open("abc.txt", "r")
line = f.readline()
while line != "":
print(line)
line = f.readline()
f.close()
Sunny Bunny Chinny Vinny Pinny Munny
In [12]:
f = open("abc.txt", "r")
line = f.readline()
while line != "":
print(line, end="")
line = f.readline()
f.close()
Sunny Bunny Chinny Vinny Pinny Munny
In [13]:
f = open("abc.txt", "r")
line = f.readline()
while line != "":
if line != "\n":
print(line, end="")
line = f.readline()
f.close()
Sunny Bunny Chinny Vinny Pinny Munny
In [14]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
['Sunny\n', 'Bunny\n', 'Chinny\n', '\n', 'Vinny\n', 'Pinny\n', 'Munny']
In [17]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
for line in data:
print(line)
['Sunny\n', 'Bunny\n', 'Chinny\n', '\n', 'Vinny\n', 'Pinny\n', 'Munny'] Sunny Bunny Chinny Vinny Pinny Munny
In [18]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
for line in data:
print(line, end="")
['Sunny\n', 'Bunny\n', 'Chinny\n', '\n', 'Vinny\n', 'Pinny\n', 'Munny'] Sunny Bunny Chinny Vinny Pinny Munny
In [23]:
f = open("abc.txt", "r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print(f.read())
Sun ny Bunn y Chinny Vinny Pinny Munny
In [28]:
# Read data from input.txt and write to output.txt?
In [29]:
f1 = open("input.txt", "r")
f2 = open("output.txt", "w")
data = f1.read()
f2.write(data)
f1.close()
f2.close()
print("Data Copied Successfully")
Data Copied Successfully
# with statement :-¶
In [31]:
with open("abc.txt", "w") as f:
f.write("DURGA\n")
f.write("SOFTWARE\n")
f.write("SOLUTIONS\n")
print("Is File Closed:", f.closed)
print("Is File Closed:", f.closed)
Is File Closed: False Is File Closed: True
In [33]:
# When we use with statement file will be closed automatically we are not required to close the file.
# The file will close automatically when we are out of with statement.
In [38]:
f1 = open("abc.txt", "w")
f2 = open("abc.txt", "a")
f2.write("hello")
f1.write("Hi")
f2.close()
f1.close()
with open("abc.txt", "r") as f:
print(f.read())
Hihellohello
In [40]:
# # Advantages of with statement :-
# 1. To group file operation in a block
# 2. To close the file automatically
In [ ]:
In [1]:
# # # Rules to Define Identifiers in Python :-
In [31]:
# 1. Allowed Characters in Python :-
# a to z
# A to Z
# 0 to 9
# _(Underscore)
In [3]:
cash = 10
In [4]:
cas$h = 10
Cell In[4], line 1 cas$h = 10 ^ SyntaxError: invalid syntax
In [5]:
cash_amount = 10
In [6]:
# 2. Identifier should not start with digit
In [7]:
total123 = 100
In [8]:
123total = 100
Cell In[8], line 1 123total = 100 ^ SyntaxError: invalid decimal literal
In [9]:
# 3. Python identifiers are case sensitive
In [10]:
total = 10
In [11]:
Total = 20
In [12]:
TOTAL = 30
In [26]:
# 4. no length limit, but not recommended to take lengthy identifiers
In [27]:
# 5. we cannot use keyword or reserved characters as identifiers
In [28]:
x = 10
In [29]:
if = 20
Cell In[29], line 1 if = 20 ^ SyntaxError: invalid syntax
In [33]:
# # Note :-
# x --> normal variable or public variable
# _x --> protected variable
# __x --> private variable
# __x__ --> magical word
# ex. __name__, __add__, __doc__, __sub__
In [37]:
__x = 10
type(__x)
Out[37]:
int
In [ ]:
# # # Reserved Words :-
In [38]:
# Some words are reserved to represent some functionality or meaning
# We have only 35 reserved words in Python
In [39]:
# True, False, None ===> Values.Reserved Literals
# and, or, not, is
# if, elif, else
# while, for, break, continue, return, in, yield
# try, except, finally, raise, assert
# import, from, as, class, def, pass, global, nonlocal, lambda, del, with
In [40]:
# # In Python 3.5 version new keyword introduced in Python :-
# async, await
# For asynchronous processing
In [6]:
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
In [9]:
# 1. All reserved words contain only alphabet symbols
# 2. The only reserved words contain upper case aplhabet symbol
# True, False, None
# 3. Switch statement is not applicable in Python
# 4. do-while loop is not there
# 5. no keywords like int, float, boolean etc
In [ ]:
In [ ]:
# # # Data Types :-
In [1]:
# Data Type Represent the type of data represented by a variable
In [3]:
x = 10
x = True
x = 10.5
# Dynamically Typed: Python, JavaScript, ShellScripting etc
In [4]:
# int x = 10;
# boolean b = true;
# Statically Typed: Java, C, C++
In [5]:
# # Types of Data Types :-
# int
# float
# complex
# bool
# str
# list
# tuple
# set
# frozenset
# dict
# bytes
# bytearray
# range
# None
In [6]:
# # The 3 most commonly used in python's in built functions :-
# In Linux everything is treated as a File
# In Python everything is treated as Object
# x = 10
# 1. print(x)
# 2. type(x)
# 3. id(x) -->Address of Object
In [7]:
x = 10
In [8]:
print(x)
10
In [12]:
type(x)
Out[12]:
int
In [13]:
id(x)
Out[13]:
140731415577672
In [14]:
x = [10, 20, 30, 40, 50, 60, 70, 80]
print(x)
print(type(x))
print(id(x))
[10, 20, 30, 40, 50, 60, 70, 80] <class 'list'> 2362951932544
In [15]:
# # # int Data Type :-
In [19]:
# To represent integral values
x = 10
print(type(x))
<class 'int'>
In [20]:
# # In Java we have :-
# byte: -128 to +127
# short: -32768 to 32767
# int: -2147483648 to 2147483647
# long: -2^63 to 2^63-1
In [21]:
x = 12134154687464634163746743216546874316574687431324865746431349874674321658746
In [22]:
# We have only 2 data types :-
# int
# long
In [23]:
# # Note :- In Python 2 we have int and long data type but in Python 3 we have only int data type
In [24]:
# # We can represent int values in multiple ways :-
# 1. Decimal Form(base-10)
# 2. Binary Form(base-2)
# 3. Octal Form(base-8)
# 4. Hexa Decimal Form(base-16)
In [28]:
# # 1. Decimal Form(base-10) :-
# The allowed digits are 0 to 9
# Example:
# x = 12345
In [32]:
# # 2. Binary Form(base-2) :-
# The allowed digits are 0 to 1
# The number should be prefixed with 0b or 0B
# Example:
# a = 0B1111
# a = 0b1111
In [34]:
a = 1111
b = 0b1111
print(a)
print(b)
print(type(a))
print(type(b))
1111 15 <class 'int'> <class 'int'>
In [35]:
# Convert Binary to Integer :-
# ( 1 1 1 1 ) = (?)
# 2^3 2^2 2^1 2^0
# 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0
# 1*8 + 1*4 + 1*2 + 1*1
# 8 + 4 + 2 + 1
# => 15
In [36]:
# # 3. Octal Form(base-8) :-
# The allowed digits are 0 to 7
# The number should be prefixed with 0o or 0O
# Example:
# a = 0O0123
# a = 0o0123
In [38]:
a = 0o0123
b = 0O0123
print(a)
print(b)
print(type(a))
print(type(b))
83 83 <class 'int'> <class 'int'>
In [39]:
# Convert Octal to Integer :-
# ( 0 1 2 3 ) = (?)
# 8^3 8^2 8^1 8^0
# 0*8^3 + 1*8^2 + 2*8^1 + 3*8^0
# 0*512 + 1*64 + 2*8 + 3*1
# 0 + 64 + 16 + 3
# => 83
In [41]:
a = 0o123
b = 0b11
print(a)
print(b)
print(a + b)
83 3 86
In [42]:
# # 4. Hexa Decimal Form(base-16) :-
# The allowed digits are:
# 0 to 9, A to F
# A-->10
# B-->11
# C-->12
# D-->13
# E-->14
# F-->15
# A - F or a - f
# The number should be prefixed with 0x or 0X
# Example:
# a = 0x0123Face
# a = 0X0123Face
In [43]:
a = 0x0123Face
b = 0X0123Face
print(a)
print(b)
print(type(a))
print(type(b))
19135182 19135182 <class 'int'> <class 'int'>
In [44]:
# Base-2 0 to 1
# Base-8 0 to 7
# Base-10 0 to 9
# Base-16 0 to 15
In [53]:
a = 0X012
print(a)
18
In [54]:
# Convert Hexa Decimal to Integer :-
# ( 0 1 2 ) = (?)
# 16^2 16^1 16^0
# 0*16^2 + 1*16^1 + 2*16*0
# 0*256 + 1*16 + 2*1
# 0 + 16 + 2
# => 18
In [55]:
# # Base Conversion Functions :-
# 1. bin()
# 2. oct()
# 3. hex()
In [ ]:
# bin(x)--> Provides Equivalent Binary Value
# x can be any value like ocatl or decimal or hexa decimal number
In [56]:
a = 10
print(a)
b = bin(a)
print(b)
10 0b1010
In [58]:
print(bin(10))
print(bin(0o10))
print(bin(0x10))
0b1010 0b1000 0b10000
In [59]:
print(oct(10))
0o12
In [60]:
print(hex(10))
0xa
In [ ]:
In [1]:
# # # Float Data Type :-
In [4]:
# Number with decimal point
f = 1.023
In [5]:
f = 0b1.1101
Cell In[5], line 1 f = 0b1.1101 ^ SyntaxError: invalid syntax
In [6]:
f = 0o1.1101
Cell In[6], line 1 f = 0o1.1101 ^ SyntaxError: invalid syntax
In [7]:
f = 0x1.1101
Cell In[7], line 1 f = 0x1.1101 ^ SyntaxError: invalid syntax
In [8]:
# Float values we should specify only in decimal format
In [11]:
# Exponential form or Scientific notation
f = 1.2e3
print(f)
1200.0
In [12]:
f = 1.2E3
print(f)
1200.0
In [14]:
# We can represent big values in less memory
a = 120000000000000000000000000000000000000
print(a)
b = 12e16
print(b)
120000000000000000000000000000000000000 1.2e+17
In [15]:
# Conditions for Float Data Type :-
# 1. with decimal point
# 2. only in decimal
# 3. exponential form
In [16]:
# # # Complex Data Type :-
In [33]:
# In C, C++, Java-->complex data type not available
# Format :-
# a+bj
# a is real number
# b is imaginary part
# j is fixed variable
# For a we can use any base
# For b we should use only decimal form
In [19]:
c = 10 + 20j
print(c)
(10+20j)
In [20]:
c = -10 -25j
print(c)
(-10-25j)
In [21]:
# For a, b we can use both int, float values
In [23]:
c = 10.5 + 20.6j
print(c)
(10.5+20.6j)
In [24]:
c = 0B1111 + 20j
print(c)
(15+20j)
In [25]:
c = 0B1111 + 0b0111j
Cell In[25], line 1 c = 0B1111 + 0b0111j ^ SyntaxError: invalid binary literal
In [27]:
a = 10 + 20j
b = 20 + 30j
print(a+b)
print(a-b)
print(a/b)
print(a*b)
(30+50j) (-10-10j) (0.6153846153846154+0.0769230769230769j) (-400+700j)
In [36]:
c = 10*20j # 10*(0+20j)
print(c)
200j
In [32]:
a = 10 + 20.5j
print(a.real)
print(a.imag)
10.0 20.5
In [34]:
a = True + 20.5j
print(a)
(1+20.5j)
In [37]:
# # # Boolean Data Type :-
In [39]:
# boolean values / logical values
# Example:
# True --> 1
# False --> 0
In [41]:
a = True
print(a)
b = False
print(b)
True False
In [42]:
# Comparison Operation:
age = 30
if age > 25:
print('AGE is greater than 25')
AGE is greater than 25
In [45]:
True + True
Out[45]:
2
In [46]:
True + False
Out[46]:
1
In [47]:
True * False
Out[47]:
0
In [48]:
True + Truej
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[48], line 1 ----> 1 True + Truej NameError: name 'Truej' is not defined
In [49]:
True + 20j
Out[49]:
(1+20j)
In [50]:
# # # Str Data Type :-
In [52]:
# str --> string
# Any sequence of character within either single quotes or double quotes
In [61]:
s = 'Pulkit'
print(s)
Pulkit
In [62]:
s = "Pulkit"
print(s)
Pulkit
In [63]:
s = Pulkit
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[63], line 1 ----> 1 s = Pulkit NameError: name 'Pulkit' is not defined
In [64]:
s = 'Pulkit"
Cell In[64], line 1 s = 'Pulkit" ^ SyntaxError: unterminated string literal (detected at line 1)
In [65]:
s = '''Pulkit
Chahal
Python
Practice'''
print(s)
Pulkit
Chahal
Python
Practice
In [66]:
# Multi line String Literals :-
# triple quotes
# triple single quotes
# triple double quotes
In [67]:
s = """Pulkit
Chahal
Python
Practice"""
print(s)
Pulkit
Chahal
Python
Practice
In [69]:
s = "Python classes by 'Durga Sir' are average"
print(s)
Python classes by 'Durga Sir' are average
In [70]:
s = 'Python classes by "Durga Sir" are average'
print(s)
Python classes by "Durga Sir" are average
In [71]:
s = 'Python 'classes' by "Durga Sir" are average'
Cell In[71], line 1 s = 'Python 'classes' by "Durga Sir" are average' ^ SyntaxError: invalid syntax
In [72]:
s = '''Python 'classes' by "Durga Sir" are average'''
print(s)
Python 'classes' by "Durga Sir" are average
In [77]:
s1 = '''Pulkit'''
s2 = 'Pulkit'
s3 = "Pulkit"
In [78]:
s1
Out[78]:
'Pulkit'
In [79]:
s2
Out[79]:
'Pulkit'
In [80]:
s3
Out[80]:
'Pulkit'
In [81]:
s = 'Python \'classes\' by "Durga Sir" are average'
print(s)
Python 'classes' by "Durga Sir" are average
In [82]:
s = "Python \'classes\' by \"Durga Sir\" are average"
print(s)
Python 'classes' by "Durga Sir" are average
In [84]:
# We use strings:-
# 1. To define multiline string literals
# 2. To use single quote or double quote as normal character
In [85]:
s = 'durga'
In [86]:
s[0]
Out[86]:
'd'
In [87]:
s[1]
Out[87]:
'u'
In [88]:
s[2]
Out[88]:
'r'
In [90]:
s[10]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[90], line 1 ----> 1 s[10] IndexError: string index out of range
In [91]:
# +ve index always from left to right
# -ve index always from right to left
In [92]:
s[-1]
Out[92]:
'a'
In [93]:
s[-2]
Out[93]:
'g'
In [94]:
s[-3]
Out[94]:
'r'
In [98]:
s[-6]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[98], line 1 ----> 1 s[-6] IndexError: string index out of range
In [99]:
s[len(s)-1]
Out[99]:
'a'
In [ ]:
In [4]:
# # # Slice Operator :-
In [81]:
# peice --> part
# [] to retreive part(slice) of the string
# s[begin:end] -> returns substring from index to end-1 index
In [12]:
s = 'abcdefghijklmnopqrstuvwxyz'
s[5:11] # begin to end-1
Out[12]:
'fghijk'
In [10]:
# If we are taking begin, then it will consider from begining of the string i.e default value is : 0
s[:8] # from 0 to 7
Out[10]:
'abcdefgh'
In [9]:
# If we are not specifying end index until end of string
s[3:] # from 3 to end of string
Out[9]:
'defghijklmnopqrstuvwxyz'
In [11]:
s[:] # from 0 to end of string
Out[11]:
'abcdefghijklmnopqrstuvwxyz'
In [14]:
# s and s[:]
In [15]:
s
Out[15]:
'abcdefghijklmnopqrstuvwxyz'
In [16]:
s[:]
Out[16]:
'abcdefghijklmnopqrstuvwxyz'
In [17]:
# Slice operaator won't raise any IndexError.
# If the index is out of range, then it will consider upto available characters only.
In [18]:
s[0:2689] # from 0 to last
Out[18]:
'abcdefghijklmnopqrstuvwxyz'
In [19]:
s[26] # IndexError: string index out of range
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[19], line 1 ----> 1 s[26] IndexError: string index out of range
In [20]:
s[3:5] # from begin index to end-1
# from 3 to 4
Out[20]:
'de'
In [1]:
s1 = 'aabcdefghijklmnopqrstuvwxyz '
In [2]:
s1[:24656874]
Out[2]:
'aabcdefghijklmnopqrstuvwxyz '
In [3]:
s1[154687:1564687463]
Out[3]:
''
In [21]:
s[2:7]
Out[21]:
'cdefg'
In [22]:
s[7:2]
Out[22]:
''
In [24]:
s[7:4] # from 7 to 3rd index in forward direction
Out[24]:
''
In [25]:
# s[begin:end:step]
In [30]:
# Print the given string with first character as uppercase
s = 'durga'
s[0].upper()+s[1:]
Out[30]:
'Durga'
In [37]:
# Print the given string with last character as uppercase
s = 'durga'
s[0:-1] + s[-1].upper()
# or
s[0:len(s)-1] + s[-1].upper()
Out[37]:
'durgA'
In [40]:
# First and last character capital
s = 'pulkitchahal'
s[0].upper() + s[1:len(s)-1] + s[-1].upper()
Out[40]:
'PulkitchahaL'
In [42]:
# # # Mathematical Operator for the String :-
In [44]:
s = 'pulkit' + 'chahal'
s
Out[44]:
'durgasoft'
In [54]:
s = ' ' + 'chahal'
s
Out[54]:
' chahal'
In [52]:
s = 'durga' + 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[52], line 1 ----> 1 s = 'durga' + 10 TypeError: can only concatenate str (not "int") to str
In [51]:
s = 10 + 'durga'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[51], line 1 ----> 1 s = 10 + 'durga' TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [55]:
s = '10' + 'durga'
s
Out[55]:
'10durga'
In [56]:
s = 'durga' + '10'
s
Out[56]:
'durga10'
In [57]:
# If we apply + operator for the strings both arguments should be str type only
In [60]:
# String Repition Operator(* -> Multiplication) ->
In [62]:
s = 'durga' * 5
s
Out[62]:
'durgadurgadurgadurgadurga'
In [65]:
s = 5 * 'durga'
s
Out[65]:
'durgadurgadurgadurgadurga'
In [63]:
s = 'durga' * 'soft'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[63], line 1 ----> 1 s = 'durga' * 'soft' TypeError: can't multiply sequence by non-int of type 'str'
In [66]:
# int + int
# str + str
# int * str
# str * int
# if we apply * for string one argument should be int
In [67]:
s = 2 * 'ab' * 3
s
Out[67]:
'abababababab'
In [69]:
# # # Fundamental data types of Python :-
# int
# float
# complex
# bool
# str
In [70]:
# # # Type Casting :-
In [71]:
# int()
# float()
# complex()
# bool()
# str()
In [72]:
# # 1. int() ->
In [80]:
# We can use this function to convert from other types to int
# int(x)
# We can convert from any type to int type except comlex type.
# If we want to convert str to int type, string should represent only integral value and should be specified only in decimal form(base-10)
In [3]:
int(10.5)
Out[3]:
10
In [74]:
int('10')
Out[74]:
10
In [77]:
int('10.5')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[77], line 1 ----> 1 int('10.5') ValueError: invalid literal for int() with base 10: '10.5'
In [75]:
int(True)
Out[75]:
1
In [76]:
int(10+20j)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[76], line 1 ----> 1 int(10+20j) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'complex'
In [78]:
int('0B1001')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[78], line 1 ----> 1 int('0B1001') ValueError: invalid literal for int() with base 10: '0B1001'
In [2]:
int('durga')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[2], line 1 ----> 1 int('durga') ValueError: invalid literal for int() with base 10: 'durga'
In [ ]:
# float --> int int(10.5)
# complex --> int int(10+20j) # Error
# bool --> int int(True)-->1
# str --> int int('123')
In [63]:
# # 2. float() :-
In [64]:
# convert from other types to float type
# int --> float float(10)
# complex --> float float(10+20j) # Error
# bool --> float float(True)
# str --> float float('10') float('10.5')
# cannot convert complex to float
# str should contains either integral value or floating point value, but compulsory we should use base-10 only
In [1]:
float(0B01010)
Out[1]:
10.0
In [65]:
float('0B01010')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[65], line 1 ----> 1 float('0B01010') ValueError: could not convert string to float: '0B01010'
In [66]:
float(10+20j)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[66], line 1 ----> 1 float(10+20j) TypeError: float() argument must be a string or a real number, not 'complex'
In [67]:
float(True)
Out[67]:
1.0
In [68]:
float('10')
Out[68]:
10.0
In [69]:
float('10.5')
Out[69]:
10.5
In [70]:
float(0X01011)
Out[70]:
4113.0
In [71]:
float('ten')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[71], line 1 ----> 1 float('ten') ValueError: could not convert string to float: 'ten'
In [ ]:
# # 3. complex() :-
In [ ]:
# from other types to complex type
# a+bj
# From any type complex is possible
# complex(x), complex(x,y)
In [ ]:
# complex(x):
# x will become real part
# imaginary part will become 0
# complex(x,y):
# x will become real part
# y will become imaginary part
In [ ]:
# The second argument can not be string.
# If the first argument is string, then we can not pass second argument.
In [72]:
complex(10)
Out[72]:
(10+0j)
In [73]:
complex(10.5)
Out[73]:
(10.5+0j)
In [74]:
complex(True)
Out[74]:
(1+0j)
In [75]:
complex('10')
Out[75]:
(10+0j)
In [76]:
complex('10.5')
Out[76]:
(10.5+0j)
In [37]:
complex('10.5j')
Out[37]:
10.5j
In [77]:
complex('ten')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[77], line 1 ----> 1 complex('ten') ValueError: complex() arg is a malformed string
In [2]:
complex(10,5)
Out[2]:
(10+5j)
In [78]:
complex(10.5,2.5)
Out[78]:
(10.5+2.5j)
In [79]:
complex(True,False)
Out[79]:
(1+0j)
In [38]:
complex('10','20')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[38], line 1 ----> 1 complex('10','20') TypeError: complex() can't take second arg if first is a string
In [39]:
complex(10,'20')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[39], line 1 ----> 1 complex(10,'20') TypeError: complex() second arg can't be a string
In [40]:
complex('10',20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[40], line 1 ----> 1 complex('10',20) TypeError: complex() can't take second arg if first is a string
In [5]:
complex(10,True)
Out[5]:
(10+1j)
In [6]:
complex(10.5,False)
Out[6]:
(10.5+0j)
In [7]:
complex(True, 10.5)
Out[7]:
(1+10.5j)
In [8]:
complex('10',True)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 1 ----> 1 complex('10',True) TypeError: complex() can't take second arg if first is a string
In [9]:
complex(0B0111, 0X10134)
Out[9]:
(7+65844j)
In [10]:
# # 4. bool() :-
In [11]:
# From other types to bool
# int --> bool zero means False and non-zero means True
# bool(0) ==> False
# bool(1) ==> True
# bool(2) ==> True
# float --> bool zero means False and non-zero means True
# bool(0.0) ==> False
# bool(0.0001) ==> True
# complex --> bool If both real and imaginary parts are zero then it is False otherwise it is True
# bool(0+0j) ==> False
# bool(0+0.1j) ==> True
# str --> bool If string is empty then False else True
# bool('True') ==> True
# bool('False') ==> True
# bool('Yes') ==> True
# bool('No') ==> True
# bool('') ==> False
In [12]:
bool(0)
Out[12]:
False
In [13]:
bool(1)
Out[13]:
True
In [14]:
bool(2)
Out[14]:
True
In [41]:
bool(-2)
Out[41]:
True
In [15]:
bool(0.0)
Out[15]:
False
In [16]:
bool(0.0001)
Out[16]:
True
In [17]:
bool(0+0j)
Out[17]:
False
In [18]:
bool(0+0.1j)
Out[18]:
True
In [19]:
bool('True')
Out[19]:
True
In [20]:
bool(' ')
Out[20]:
True
In [21]:
bool('')
Out[21]:
False
In [22]:
bool('False')
Out[22]:
True
In [23]:
# # 5. str() :-
In [24]:
# can convert any type to str
In [25]:
str(10)
Out[25]:
'10'
In [26]:
str(10.5)
Out[26]:
'10.5'
In [27]:
str(10+20j)
Out[27]:
'(10+20j)'
In [28]:
str(True)
Out[28]:
'True'
In [29]:
str(0B01111)
Out[29]:
'15'
In [30]:
# # # Fundamental Data Types Vs Immutability :-
In [31]:
# All Fundamental Data Types are immutable
# In Python everything is treated as object only
# Immutable ==> we cannot change
# Once we creates an object, we cannot change its content.
# If we are trying to change the content, with those cahnges a new object will be created.
In [42]:
x = 10
y = x
print(id(x))
print(id(y))
140731415577672 140731415577672
In [43]:
y = y+1
print(id(x))
print(id(y))
140731415577672 140731415577704
In [44]:
x = True
print(id(x))
y = False
print(id(y))
140731414104640 140731414104672
In [46]:
x = 10
print(id(x))
x = float(x)
print(id(x))
140731415577672 1348341995856
In [47]:
x = 10
print(id(x))
x = x+1
print(id(x))
140731415577672 140731415577704
In [ ]:
In [1]:
# # # Fundamental Data Types :-
# int, float, complex, bool, str
# # # Immutability
In [4]:
# # # Immutability Concept :-
In [5]:
# PVM ==> Intelligent
In [3]:
a = 10
b = 10
c = 10
print(id(a))
print(id(b))
print(id(c))
140709893870664 140709893870664 140709893870664
In [6]:
# With Immutability :-
# 1. Memory utilization will be improved.
# 2. Performace also will be improved.
In [6]:
a = 10.5
b = 10.5
print(id(a))
print(id(b))
print(a is b)
2189640694544 2189669176080 False
In [13]:
a = 10
b = 10
print(id(a))
print(id(b))
print(a is b)
140731415577672 140731415577672 True
In [15]:
a = 256
b = 256
print(id(a))
print(id(b))
print(a is b)
140731415585544 140731415585544 True
In [16]:
a = 257
b = 257
print(id(a))
print(id(b))
print(a is b)
2189662697680 2189669186096 False
In [8]:
a = True
b = True
print(id(a))
print(id(b))
print(a is b)
140731414104640 140731414104640 True
In [9]:
a = 'hi'
b = 'hi'
print(id(a))
print(id(b))
print(a is b)
2189573497072 2189573497072 True
In [17]:
a = 10+20j
b = 10+20j
print(id(a))
print(id(b))
print(a is b)
2189669171984 2189669185744 False
In [ ]:
# # Note :- For Previous Python Versions ==>
# For two different variables(a, b) id will be same except for float type and complex type.
# For new Python Versions ==>
# For two different variables(a, b) id will be same for all type.
In [17]:
# Search for an object is available or not?
In [18]:
# Immutability :-
# Once we creates an object, we cannot change content of that object.
# If we are trying to change, with those changes a new object wil be created.
In [23]:
# Till how much value reuse can be done?
# int ==> 0 to 256
In [29]:
l = [10, 20, 30, 40]
print(l)
print(id(l))
l[0] = 7777
print(l)
print(id(l))
[10, 20, 30, 40] 1597873346176 [7777, 20, 30, 40] 1597873346176
In [30]:
# If variavble is saved in stack and object in heap, then ID of v1, v2, v3 etc should be different from object ' HYDERABAD' itself..
# How would we check ID or addreass of variable itself?
# id(v1) --> Address of object pointed by v1
# id(v2)
In [31]:
# # Note :- All Fundamental Data Types are Immutable.
# ex. int, float, bool, complex, str
In [18]:
l1 = [10, 20, 30, 40]
l2 = l1
print(l1)
print(l2)
l1[0] = 777
print(l1)
print(l2)
l2[1] = 888
print(l1)
print(l2)
print(id(l1))
print(id(l2))
print(l1 is l2)
[10, 20, 30, 40] [10, 20, 30, 40] [777, 20, 30, 40] [777, 20, 30, 40] [777, 888, 30, 40] [777, 888, 30, 40] 2189669521536 2189669521536 True
In [19]:
l1 = [10, 20, 30, 40]
l2 = [10, 20, 30, 40]
print(l1)
print(l2)
print(id(l1))
print(id(l2))
print(l1 is l2)
[10, 20, 30, 40] [10, 20, 30, 40] 2189669519232 2189669540416 False
In [40]:
# # # Collection Related Data Types :-
In [41]:
a = 10
b = 10.5
c = True
d = 'durga'
In [42]:
name = 'durga'
names = ['durga', 'ravi', 'shiva']
In [43]:
# Collection Related Data Types :-
# list
# tuple
# set
# frozenset
# dict
# bytes
# bytearray
# range
In [ ]:
# [] ==> list
# () ==> tuple
# {} ==> set
# {100:'durga', 200:'ravi'} ==> dict
In [46]:
# # list :-
In [47]:
# If we want to represent a group of values as a single entity where insertoion oreder preserved and duplicates are allowed.
In [49]:
list = [10, 10.5, 'durga', True, 10, 10, 10.5]
list
Out[49]:
[10, 10.5, 'durga', True, 10, 10, 10.5]
In [69]:
# Properties of List :-
# 1. Insertion order preserved.
# 2. Duplicates are allowed.
# 3. Heterogeneous objects are alllowed.
# 4. Values should be enclosed within [].
# 5. Index and slice are applicable.
# 6. Growable in nature.
# 7. Mutable
In [54]:
list[0]
Out[54]:
10
In [57]:
list[-1]
Out[57]:
10.5
In [58]:
list[2:5]
Out[58]:
['durga', True, 10]
In [60]:
list[0:9:2]
Out[60]:
[10, 'durga', 10, 10.5]
In [61]:
list
Out[61]:
[10, 10.5, 'durga', True, 10, 10, 10.5]
In [62]:
list.append('ravi')
In [63]:
list
Out[63]:
[10, 10.5, 'durga', True, 10, 10, 10.5, 'ravi']
In [64]:
list.append('shiva')
In [66]:
list
Out[66]:
[10, 10.5, 'durga', True, 10, 10, 10.5, 'ravi', 'shiva']
In [67]:
list.remove(10)
In [68]:
list
Out[68]:
[10.5, 'durga', True, 10, 10, 10.5, 'ravi', 'shiva']
In [ ]:
In [57]:
# # Tuple Data Type :-
In [58]:
# It is exactly same as list except that it is immutable
# Read only version of List ==> Tuple
In [59]:
# Tuple Properties :-
# 1. Insertion Order is preserved.
# 2. Indexing and slicing concepts are applicable.
# 3. Duplicates are allowed.
# 4. Heterogenous Objects are allowed.
# 5. ()
# 6. Immutable
# 7. Not Growable
In [60]:
tuple = (10, 20, 30, 40, 10, 'durga', True, 10.5)
tuple
Out[60]:
(10, 20, 30, 40, 10, 'durga', True, 10.5)
In [61]:
tuple[0]
Out[61]:
10
In [62]:
tuple[0:5]
Out[62]:
(10, 20, 30, 40, 10)
In [63]:
tuple[0:6:2]
Out[63]:
(10, 30, 10)
In [64]:
tuple.append(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[64], line 1 ----> 1 tuple.append(10) AttributeError: 'tuple' object has no attribute 'append'
In [94]:
tuple.remove(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[94], line 1 ----> 1 tuple.remove(10) AttributeError: 'tuple' object has no attribute 'remove'
In [93]:
# If content is not fixed and keep om changing ==> List
# Facebook comment: comment
In [84]:
# If content is fixed and won't change ==> Tuple
# Bank account type: Saving or Current
In [85]:
l = [10, 20, 30, 40]
# more memory
In [86]:
t = (10, 20, 30, 40)
# less memory
In [87]:
# Accessing elements is also very fast in Tuple.
# Performance is more for Tuple.
In [88]:
# # Difference b/w List and Tuple : -
# List :-
# 1. Mutable
# 2. [] (Square Brackets)
# 3. More Memory
# 4. Low Performance
# 5. Content not Fixed
# 6. Growable
# 7. Dynamic in Nature
# Tuple :-
# 1. Unmutable
# 2. () (Round Brackets or Parentheses)
# 3. Less Memory
# 4. More Performance
# 5. Content Fixed
# 6. Not Growable
# 7. Static in Nature
In [89]:
t = () # 0 elements
type(t)
Out[89]:
tuple
In [90]:
t = (10) # 1 elements is not tuple untill ',' is not present
type(t)
Out[90]:
int
In [91]:
t = (10,)
type(t)
Out[91]:
tuple
In [92]:
t = (,)
type(t)
Cell In[92], line 1 t = (,) ^ SyntaxError: invalid syntax
In [ ]:
l = [10]
type(l)
Out[ ]:
list
In [ ]:
l = [,]
Cell In[27], line 1 l = [,] ^ SyntaxError: invalid syntax
In [ ]:
t = 10,20,30,40
type(t)
Out[ ]:
tuple
In [ ]:
# In case of Tuple Parantheses are optional
In [ ]:
t = 10
type(t)
Out[ ]:
int
In [ ]:
t = 10,
type(t)
Out[ ]:
tuple
In [ ]:
# # Set Data Type :-
In [ ]:
# Properties of Set:-
# 1. Dupicates are not allowed
# 2. Order is not Important
# 3. Indexing and Slicing concepts are not applicable
# 4. Heterogeneous objects are allowed
# 5. Mutable
# 6. Growable
# 7. {}
In [ ]:
set = {10,20,-30,'durga','apple',10.5,10,20,10.5,'durga','shyam'}
set
Out[ ]:
{-30, 10, 10.5, 20, 'apple', 'durga', 'shyam'}
In [ ]:
type(set)
Out[ ]:
set
In [ ]:
# Examplpe -->
# sms sending application:
# sms for unique numbers in any order
In [ ]:
for x in set:
print(x)
-30 10.5 20 apple shyam 10 durga
In [ ]:
set.append(50)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[48], line 1 ----> 1 set.append(50) AttributeError: 'set' object has no attribute 'append'
In [ ]:
set.add(50)
In [ ]:
set
Out[ ]:
{-30, 10, 10.5, 20, 50, 'apple', 'durga', 'shyam'}
In [ ]:
set.remove('durga')
set
Out[ ]:
{-30, 10, 10.5, 20, 50, 'apple', 'shyam'}
In [ ]:
# Difference b/w List and Set :-
# List :-
# 1. Duplicates Allowed
# 2. Order preserved
# 3. Indexing and Slicing Concepts are applicable
# 4. []
# Set :-
# 1. Duplicates Not Allowed
# 2. Order not preserved
# 3. Indexing and Slicing Concepts are not applicable
# 4. {}
In [1]:
# # Note :- How to Create Empty Set
s = {}
print(type(s)) # beacuse dict is most common used
s = set()
print(type(s)) # set
print(len(s)) # 0
print(s) # set()
<class 'dict'> <class 'set'> 0 set()
In [ ]:
# # Frozenset :-
In [ ]:
# It is exactly same as set except that it is immutable.
In [ ]:
s = {10,20,30,'durga',10.5,True,10,False}
s
Out[ ]:
{10, 10.5, 20, 30, False, True, 'durga'}
In [ ]:
type(s)
Out[ ]:
set
In [ ]:
fs = frozenset(s)
fs
Out[ ]:
frozenset({10, 10.5, 20, 30, False, True, 'durga'})
In [ ]:
type(fs)
Out[ ]:
frozenset
In [ ]:
fs.add(50)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[7], line 1 ----> 1 fs.add(50) AttributeError: 'frozenset' object has no attribute 'add'
In [ ]:
fs.remove(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[8], line 1 ----> 1 fs.remove(10) AttributeError: 'frozenset' object has no attribute 'remove'
In [ ]:
In [1]:
# # dict Data Type :-
In [2]:
# list ==> [10, 20, 30, 40]
# tuple ==> (10, 20, 30, 40)
# set ==> {10, 20, 30, 40}
# frozenset ==> frozenset({10, 20, 30, 40})
# All these data types can hold individual values.
# key-value pairs are
# rollno --> name
# name --> mail id
In [3]:
# dict --> dictionary
# [] --> list
# () --> tuple
# {} --> set
# {} --> dict
In [5]:
d = {100:'durga', 200:'ravi', 300:'shiva'}
print(d)
print(type(d))
{100: 'durga', 200: 'ravi', 300: 'shiva'}
<class 'dict'>
In [6]:
d = {}
print(type(d))
<class 'dict'>
In [12]:
d = {}
print(d)
{}
In [13]:
# d[key] = value
d[100] = 'sunny'
d[200] = 'bunny'
d[300] = 'chinny'
print(d)
{100: 'sunny', 200: 'bunny', 300: 'chinny'}
In [14]:
print(d[100])
sunny
In [15]:
# Properties of dictionary DataType :-
# 1. Order is not preserved
# 2. Indexing and Slicing concepts are not applicable
# 3. For keys and values we can use any data type no restrictions.
# 4. keys and values can be hetrogeneous
# 5. duplicate keys are not allowed but values can be duplicate
# 6. If we are trying to add entry with duplicate key, then old value will be replaced with new value
# 7. Mutable
In [16]:
d = {100:'ravi', 'durga':200}
print(d)
{100: 'ravi', 'durga': 200}
In [17]:
d = {a:'durga', b:'abhi'}
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[17], line 1 ----> 1 d = {a:'durga', b:'abhi'} NameError: name 'a' is not defined
In [19]:
a = 100
b = 200
d = {a:'durga', b:'abhi'}
print(d)
{100: 'durga', 200: 'abhi'}
In [20]:
d = {100:'durga', 200:'ravi'}
# keys: 100, 200
# values: 'durga', 'rqavi'
In [22]:
d = {100:'ravi', 200:'durga', 100:'durga', 200:'ravi'}
print(d)
{100: 'durga', 200: 'ravi'}
In [23]:
d = {100:'durga'}
print(d)
d[100] = 'ravi'
print(d)
{100: 'durga'}
{100: 'ravi'}
In [24]:
d = {100:['durga', 'ravi', 'shiva']}
print(d)
{100: ['durga', 'ravi', 'shiva']}
In [25]:
d = {100:'abc', '100':'xyz'}
print(d)
{100: 'abc', '100': 'xyz'}
In [26]:
# # Range Data Type :-
In [31]:
# range means sequence of values
# 0 to 9
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
In [32]:
r = range(10)
print(r)
print(type(r))
range(0, 10) <class 'range'>
In [33]:
for x in r:
print(x)
0 1 2 3 4 5 6 7 8 9
In [60]:
# Properties of Range Data Type :-
# Sequence
# form-1:
# range(n) ==> 0 to n-1 values can be represented
# form-2:
# range(begin, end) ==> from begin value to end-1
# form-3:
# range(begin, end, increment/decrement value) ==> from begin value to end-1 and increment/decrement
# Indexing and slicing also applicable
# Immutable
In [61]:
r = range(2,8)
for x in r:
print(x)
2 3 4 5 6 7
In [62]:
r = range(1,11)
for x in r:
print(x)
1 2 3 4 5 6 7 8 9 10
In [63]:
r = range(1,11,2)
for x in r:
print(x)
1 3 5 7 9
In [64]:
r = range(11,1,-2)
for x in r:
print(x)
11 9 7 5 3
In [65]:
r = range(1,11,3)
for x in r:
print(x)
1 4 7 10
In [66]:
l = []
r = range(0,101,5)
for x in r:
l.append(x)
print(l)
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
In [67]:
r = range(1,11,-1)
for x in r:
print(x)
In [68]:
r = range(10)
print(r)
print(r[0])
range(0, 10) 0
In [69]:
print(r[2])
2
In [70]:
print(r[5])
5
In [71]:
print(r[-1])
9
In [72]:
print(r[2:5])
range(2, 5)
In [73]:
print(r[2:8:2])
range(2, 8, 2)
In [74]:
r[1] = 7777
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[74], line 1 ----> 1 r[1] = 7777 TypeError: 'range' object does not support item assignment
In [75]:
# # bytes Data Type :-
In [76]:
# If we want tot represent a group of values within the range 0 to 255
In [ ]:
# Properties of byte Data Type :-
# 1. Indexing and slicing applicable
# 2. Values should be in range 0 to 255
# 3. Immutable
# 4. b = bytes()
In [78]:
l = [10, 20, 30, 40]
b = bytes(l)
print(type(b))
print(b)
<class 'bytes'>
b'\n\x14\x1e('
In [79]:
l = [10, 20, 30, 40, 256]
b = bytes(l)
print(type(b))
print(b)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[79], line 3 1 l = [10, 20, 30, 40, 256] ----> 3 b = bytes(l) 5 print(type(b)) 6 print(b) ValueError: bytes must be in range(0, 256)
In [80]:
print(b[0])
10
In [81]:
print(b[2])
30
In [82]:
print(b[-1])
40
In [84]:
for x in bytes[1:3]:
print(x)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[84], line 1 ----> 1 for x in bytes[1:3]: 2 print(x) TypeError: type 'bytes' is not subscriptable
In [85]:
for x in b[1:3]:
print(x)
20 30
In [86]:
l = [10, 20, 30, 40]
b = bytes(l)
b[0] = 777
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[86], line 5 1 l = [10, 20, 30, 40] 3 b = bytes(l) ----> 5 b[0] = 777 TypeError: 'bytes' object does not support item assignment
In [89]:
# list --> mutable
# tuple --> immutable
# set --> mutable
# frozenset --> immutable
# dict --> mutable
# range --> immutable
# bytes --> immutable
# bytearray --> mutable
In [90]:
# # bytearray Data Type :-
In [91]:
# It is exactly same as bytes except that it is mutable.
In [92]:
l = [10, 20, 30, 40]
b = bytearray(l)
print(type(b))
<class 'bytearray'>
In [93]:
l = [10, 20, 30, 40, 256]
b = bytearray(l)
print(type(b))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[93], line 3 1 l = [10, 20, 30, 40, 256] ----> 3 b = bytearray(l) 5 print(type(b)) ValueError: byte must be in range(0, 256)
In [94]:
l = [10, 20, 30, 40]
b = bytearray(l)
b[0] = 15
In [96]:
for x in b:
print(x)
15 20 30 40
In [ ]:
In [1]:
# # Data Types :-
In [2]:
# int flaot complex bool str
# list tuple
# set frozenset
# dict
# range
# bytes bytearray
In [3]:
# 1. In general bytes and bytearray types can be used to represent binary information like images, video files etc.
# 2. Long data type avaliable in Python2x but not in Python3x long values also can be represented as int type only
# 3. char data type 'a' as str type
In [4]:
# # None Data Type :-
In [11]:
# None means nothing or no value associated.
# If the value is not available, to handle such type of requirements None (null in Java)
# None --> no value associated
# None is also an object in Python
x = None
print(x)
print(id(x))
print(type(x))
None 140731371719440 <class 'NoneType'>
In [12]:
def f1():
return 10
r = f1()
print(r)
10
In [13]:
def f1():
print('hello')
r = f1()
print(r)
hello None
In [14]:
# Only one None value will be created in python
In [16]:
a = None
b = None
c = None
def f1():
pass
r = f1()
print(a)
print(id(a))
print(type(a))
print(b)
print(id(b))
print(type(b))
print(c)
print(id(c))
print(type(c))
print(r)
print(id(r))
print(type(r))
None 140731371719440 <class 'NoneType'> None 140731371719440 <class 'NoneType'> None 140731371719440 <class 'NoneType'> None 140731371719440 <class 'NoneType'>
In [17]:
# # Escape Characters :-
In [52]:
# The characters associated with some special meaning
# \n --> New Line
# \t --. Horizontal Tab
# \r --> Carriage Return
# \b --> Backspace
# \f --. Form Feed
# \v --> Vertical Tab
# \' --> Single Quote
# \" --> Double Quote
# \\ --> Backslash Symbol
# etc
In [53]:
s = 'durga\tsoft'
print(s)
durga soft
In [54]:
s = 'durga\nsoft'
print(s)
durga soft
In [55]:
s = 'durga\rtsoft'
print(s)
tsoft
In [56]:
s = 'durga\bsoft'
print(s)
durgsoft
In [57]:
s = 'durga\fsoft'
print(s)
durga soft
In [58]:
s = 'durga\vsoft'
print(s)
durga soft
In [59]:
s = 'durga\'sof\'t'
print(s)
durga'sof't
In [60]:
s = 'durga\"sof\"t'
print(s)
durga"sof"t
In [61]:
s = 'C:\\Python\\Practice'
In [62]:
# # Comments :-
In [63]:
# Single Line Comment:
# This is code
s = 'pulkit' # code output: 'pulkit'
In [64]:
# Multi-Line Comment:
# There is no special symbol for multiline comments
'''
This is
Multi-Line
Comment
''' # This is Documentation String but not Comment
"""
This is
Multi-Line
Comment
""" # This is Documentation String but not Comment
s = 'pulkit'
In [65]:
# Triple Quotes can be used for:-
# 1. To define multiline string literals
# 2. To use ' or " as symbols
# 3. To define docstring
In [66]:
# # Constants :-
In [67]:
# Constants concept not applicable in Python
# MAX_VALUE = 10 # it is constant doesn't change its value
# max_value = 10
In [68]:
MAX_VALUE = 10
print(type(MAX_VALUE))
<class 'int'>
In [ ]:
In [3]:
# set --> unique elements(no duplicates)
# order is not important
s = {10, 20, 30, 40}
s.add(50)
print(s)
{40, 10, 50, 20, 30}
In [4]:
# unique elements(no duplicates)
# order is not important
# frozenset
s = {10, 20, 30, 40}
fs = frozenset(s)
fs.add(50)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[4], line 7 5 s = {10, 20, 30, 40} 6 fs = frozenset(s) ----> 7 fs.add(50) AttributeError: 'frozenset' object has no attribute 'add'
In [6]:
# bytes and bytearray
# 0 to 255
# bytes --> immutable
# bytearray --> mutable
# images, video files and audio files etc
In [7]:
l = [10, 20, 30, 40]
b = bytes(l)
for x in b:
print(x)
10 20 30 40
In [8]:
b[0] = 50
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 1 ----> 1 b[0] = 50 TypeError: 'bytes' object does not support item assignment
In [9]:
l = [10, 20, 30, 40]
b = bytearray(l)
for x in b:
print(x)
10 20 30 40
In [10]:
b[0] = 50
In [11]:
for x in b:
print(x)
50 20 30 40
In [12]:
print('# this is comment')
# this is comment
# # Operators :-¶
In [16]:
# Telephone Operator
# Camera Operator
# # Types of Operators:-
# 1. Arithmetic Operators
# 2. Relational Operators
# 3. Logical Operators
# 4. Bitwise Operators
# 5. Assignment Operators
# 6. Special Operators
# 1. Arithmetic Operators :-¶
In [39]:
# + --> Addition
# - --> Subtraction
# * --> Multiplication
# / --> Division
# % --> Modulo Operator
# // --> Floor Division Operator
# ** --> Exponent Operator or Power Operator
In [42]:
10+2
Out[42]:
12
In [43]:
10-2
Out[43]:
8
In [44]:
10*2
Out[44]:
20
In [57]:
10%2
Out[57]:
0
In [58]:
# # Note:-
# The result of '/' division operator is always float type
# // result is either int type or float type
# If both arguments are int type result is int type only
# If atleast one argument is float type result is float type
In [66]:
10/2
Out[66]:
5.0
In [59]:
10//2
Out[59]:
5
In [60]:
23/6
Out[60]:
3.8333333333333335
In [69]:
23//6
Out[69]:
3
In [70]:
1.2//2
Out[70]:
0.0
In [71]:
# 1.56 ->
# floor int value ==> 1
# floor float value ==> 1.0
# ceil int value ==> 2
# ceil float value ==> 2.0
In [72]:
10.0/2
Out[72]:
5.0
In [73]:
10.0//2
Out[73]:
5.0
In [74]:
10/3
Out[74]:
3.3333333333333335
In [75]:
10//3
Out[75]:
3
In [78]:
10.0/3
Out[78]:
3.3333333333333335
In [79]:
10.0//3
Out[79]:
3.0
In [80]:
# * --> multiplication
# ** --> exponential or power
In [83]:
10**3 # 10 * 10 * 10
Out[83]:
1000
In [84]:
3**3 # 3 * 3 * 3
Out[84]:
27
In [85]:
3***3
Cell In[85], line 1 3***3 ^ SyntaxError: invalid syntax
In [86]:
3.0**3
Out[86]:
27.0
In [88]:
3**3*2
Out[88]:
54
In [89]:
10**-3
Out[89]:
0.001
In [90]:
10**2.8
Out[90]:
630.957344480193
In [91]:
3//2
Out[91]:
1
In [92]:
# + and * :-
# + operator applicable for str type also
# concatenation operator
In [94]:
s = 'durga' + 'soft'
print(s)
durgasoft
In [96]:
'durga' + str(10)
Out[96]:
'durga10'
In [97]:
int('durga')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[97], line 1 ----> 1 int('durga') ValueError: invalid literal for int() with base 10: 'durga'
In [99]:
'durga' + 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[99], line 1 ----> 1 'durga' + 10 TypeError: can only concatenate str (not "int") to str
In [100]:
# Problem with Value ValueError
# Problem with Type TypeError
In [101]:
'durga' * 3
Out[101]:
'durgadurgadurga'
In [102]:
'durga' * 'durga'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[102], line 1 ----> 1 'durga' * 'durga' TypeError: can't multiply sequence by non-int of type 'str'
In [106]:
'durga' * int('10')
Out[106]:
'durgadurgadurgadurgadurgadurgadurgadurgadurgadurga'
In [107]:
# + --> both arguments should be str type or int type
# * --> one arg str and one arg int
In [109]:
'durga' * 10.0
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[109], line 1 ----> 1 'durga' * 10.0 TypeError: can't multiply sequence by non-int of type 'float'
In [110]:
10/0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[110], line 1 ----> 1 10/0 ZeroDivisionError: division by zero
In [111]:
10.0/0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[111], line 1 ----> 1 10.0/0 ZeroDivisionError: float division by zero
In [112]:
'abc' * 0
Out[112]:
''
# 2. Relational Operators :-¶
In [114]:
# <, <=, >, >=
In [116]:
a = 10
b = 20
In [117]:
a < b
Out[117]:
True
In [118]:
a <= b
Out[118]:
True
In [119]:
a > b
Out[119]:
False
In [120]:
a >= b
Out[120]:
False
In [122]:
# string values also comparison is bsaed on unicode value/ascii value
# a --> 97
# b --> 98
# c --> 99
# A --> 65
# B --> 66
# C --> 67
In [123]:
a = 'durga'
b = 'ravi'
In [124]:
a < b
Out[124]:
True
In [125]:
a <= b
Out[125]:
True
In [126]:
a > b
Out[126]:
False
In [127]:
a >= b
Out[127]:
False
In [128]:
a = 'durga'
b = 'Durga'
In [129]:
a < b
Out[129]:
False
In [130]:
a <= b
Out[130]:
False
In [131]:
a > b
Out[131]:
True
In [132]:
a >= b
Out[132]:
True
In [135]:
ord('d')
Out[135]:
100
In [136]:
ord('D')
Out[136]:
68
In [137]:
ord('a') * ord('b')
Out[137]:
9506
In [138]:
ord('a') + ord('b')
Out[138]:
195
In [144]:
# from char find ascii value
# ord()
# from ascii value to char value
# chr()
# char --> ord()
# ascii --> chr()
In [140]:
chr(99)
Out[140]:
'c'
In [141]:
chr(10)
Out[141]:
'\n'
In [143]:
chr(72) + chr(99)
Out[143]:
'Hc'
In [145]:
# for boolean types
# True --> 1
# Fasle -->
In [146]:
a = True
b = False
In [147]:
a > b
Out[147]:
True
In [148]:
a >= b
Out[148]:
True
In [149]:
a < b
Out[149]:
False
In [150]:
a <= b
Out[150]:
False
In [151]:
'durga' < 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[151], line 1 ----> 1 'durga' < 10 TypeError: '<' not supported between instances of 'str' and 'int'
In [153]:
a = True
b = 10
In [154]:
a > b
Out[154]:
False
In [155]:
a < b
Out[155]:
True
In [156]:
2**2 < 5
Out[156]:
True
In [157]:
2**2 > 5
Out[157]:
False
In [158]:
'a' > '297'
Out[158]:
True
In [160]:
ord('a')
Out[160]:
97
In [161]:
ord('2')
Out[161]:
50
In [163]:
ord('a') > ord('2')
Out[163]:
True
In [164]:
10 < 20
Out[164]:
True
In [165]:
10 < 20 < 30
Out[165]:
True
In [166]:
10 < 20 < 30 < 40
Out[166]:
True
In [167]:
10 < 20 < 30 < 40 > 50
Out[167]:
False
In [184]:
# Chaning of Relational Operators:-
# If all comparison returns True then the result is True.
# If atleast one comparison returns False then the result is False.
# Equality Operators :-¶
In [3]:
# == and !=
# always meant for content comparosion
In [4]:
10 == 20
Out[4]:
False
In [5]:
10 == 10
Out[5]:
True
In [6]:
10.5 == 10
Out[6]:
False
In [7]:
10.0 == 10
Out[7]:
True
In [8]:
'durga' == 'ravi'
Out[8]:
False
In [9]:
'durga' == 10
Out[9]:
False
In [10]:
True == False
Out[10]:
False
In [11]:
True == 1
Out[11]:
True
In [12]:
ord('d')
Out[12]:
100
In [13]:
'd' == 100
Out[13]:
False
In [17]:
ord('d') == 100
Out[17]:
True
In [14]:
# == --> operator for content comparosion
# = --> means assignment
In [15]:
True == 1.0
Out[15]:
True
In [16]:
ord('a') == 97
Out[16]:
True
In [18]:
# Chaning of Equality Operators:-
# If all comparison returns True then the result is True.
# If atleast one comparison returns False then the result is False.
In [19]:
10 == 20 == 30 == 40
Out[19]:
False
In [20]:
10 == 10.0 == 10 == 10.0
Out[20]:
True
In [21]:
1 == 1.0 == True == 1.0
Out[21]:
True
# == operator and is operator¶
In [22]:
# == operator meant for content comparosion
# is operator meant for reference comparosion(address comparison)
# is operator returns True if both refrences are pointing to the same object address.
In [25]:
l1 = [10, 20, 30, 40]
l2 = [10, 20, 30, 40]
print(id(l1))
print(id(l2))
print(l1 is l2)
print(l1 == l2)
1444155477056 1444155379712 False True
In [26]:
l1 = [10, 20, 30, 40]
l2 = l1
print(id(l1))
print(id(l2))
print(l1 is l2)
print(l1 == l2)
1444155476352 1444155476352 True True
# 3. Logical Operators :-¶
In [27]:
# and
# or
# not
In [28]:
# For boolean Types :-
# and --> If both arguments are True then only result is True
# or --> If atleast one argument is True then result is True
# not --> complement
In [29]:
True and True
Out[29]:
True
In [30]:
True and False
Out[30]:
False
In [31]:
False and True
Out[31]:
False
In [32]:
False and False
Out[32]:
False
In [33]:
not True
Out[33]:
False
In [34]:
not False
Out[34]:
True
In [35]:
True or True
Out[35]:
True
In [36]:
True or False
Out[36]:
True
In [37]:
False or True
Out[37]:
True
In [38]:
False or False
Out[38]:
False
In [42]:
# For non-Boolean Types :-
# zero consider as False
# non-zero consider as True
# empty string, set, list, tuple etc considered as False
# non-empty considered as True
# For non-Boolean Types we are not getting True or False.
In [43]:
# and Operator :-
# x and y ->
# if x evalutes to True then the result is y
# if x evalutes to False then the result is x
In [44]:
10 and 20
Out[44]:
20
In [45]:
0 and 10
Out[45]:
0
In [46]:
'' and 10
Out[46]:
''
In [47]:
'as' and 10
Out[47]:
10
In [48]:
# or Operator :-
# x or y ->
# If x evaluates to True then the result is x
# If x evaluates to False then the result is y
In [49]:
10 or 20
Out[49]:
10
In [50]:
0 or 10
Out[50]:
10
In [51]:
10 or 0
Out[51]:
10
In [52]:
'' or 'durga'
Out[52]:
'durga'
In [53]:
'durga' or ''
Out[53]:
'soft'
In [54]:
0 or 0
Out[54]:
0
In [1]:
not 10
Out[1]:
False
In [2]:
not ''
Out[2]:
True
In [3]:
not 0
Out[3]:
True
In [4]:
not 'durga'
Out[4]:
False
In [ ]:
# 4. Bitwise Operators :-¶
In [5]:
# & --> AND
# | --> OR
# ^ --> X-OR
# ~ --> Bitwise Complement Operator
# << --> Left Shift Operator
# >> --> Right Shift Operator
# Applicable only for:-
# int type and boolean type
In [2]:
10 & 11
Out[2]:
10
In [3]:
True & False
Out[3]:
False
In [4]:
10.5 & 11.6
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 1 ----> 1 10.5 & 11.6 TypeError: unsupported operand type(s) for &: 'float' and 'float'
In [6]:
# & --> If both bits are 1 then result is 1
# | --> If atleast one bit is 1 then result is 1
# ^ --> If both bits are different then result is 1
# if both bits are same then result is 0
In [11]:
a = 4 # 4 --> 1 0 0
b = 5 # 5 --> 1 0 1
a & b # 1 0 0
Out[11]:
4
In [12]:
a = 4 # 4 --> 1 0 0
b = 5 # 5 --> 1 0 1
a | b # 1 0 1
Out[12]:
5
In [13]:
a = 4 # 4 --> 1 0 0
b = 5 # 5 --> 1 0 1
a ^ b # 0 0 1
Out[13]:
1
In [14]:
# Bitwise Complement Operator(~) :-
In [19]:
~4
Out[19]:
-5
In [16]:
~9
Out[16]:
-10
In [17]:
~-5
Out[17]:
4
In [18]:
~-20
Out[18]:
19
In [20]:
# 32 bits
# The most significant bit(MSB) acts as sign bit
# 0 means +ve number
# 1 means -ve number
# positive numbers will be represented directly in the memory
# But negative numbers will be represented indirectly in the memory in 2's complement form
# 2's complement form = 1's complement form+1
# 1's complement form = intrchange 0s and 1s
In [22]:
# 4 = 0000000000.....000000100
# ~4 = 1111111111.....111111011 ==> -5
In [23]:
# Shift Operators :-
In [24]:
# << and >>
# << --> Left Shift
# >> --> Right Shift
In [32]:
# << --> Left Shift :-
# extra cells are always filled with zero
In [37]:
10 << 2
# 10 --> 00000000000....0000000001010
# 10<< --> 000000000....0000000101000
Out[37]:
40
In [28]:
4 << 2
# 4 --> 00000000000....0000000000100
# 4<< --> 000000000....0000000010000
Out[28]:
16
In [33]:
# >> --> Right Shift :-
# extra cells are always filled with sign bit
# +ve number zero(0)
# -ve number one(1)
In [34]:
10 >> 2
# 10 --> 00000000000....0000000001010
# 10>> --> 00000000000000000....000000010
Out[34]:
2
In [35]:
4 >> 2
# 4 --> 00000000000....0000000000100
# 4<< --> 00000000000000000....000000001
Out[35]:
1
In [41]:
-10 >> 2
# 10 --> 00000000000....0000000001010
# 1's complement --> 11111111111....1111111110101
# 1
# 2's complement --> 11111111111....1111111110110
# -10 --> 11111111111....1111111110110
# -10>> --> 111111111111111....11111111101 # -ve as first value is 1
# 2's complement --> 000000000000000....00000000010
# 1
# --> 000000000000000....00000000011
# Value is -ve so ans is -3
Out[41]:
-3
In [38]:
10 >> -3
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[38], line 1 ----> 1 10 >> -3 ValueError: negative shift count
In [42]:
True & True
Out[42]:
True
In [43]:
True | True
Out[43]:
True
In [44]:
True ^ False
Out[44]:
True
In [45]:
False ^ True
Out[45]:
True
In [46]:
~True
Out[46]:
-2
In [47]:
~False
Out[47]:
-1
In [49]:
True >> 2
Out[49]:
0
In [50]:
False >> 2
Out[50]:
0
In [51]:
True << 2
Out[51]:
4
In [52]:
False << 2
Out[52]:
0
In [53]:
False << 4
Out[53]:
0
In [54]:
False << 4
Out[54]:
0
In [ ]:
# 5. Assignment Operators :-¶
In [6]:
# assignment combined with some other operators: compound assignment operator
# +=
# -=
# *=
# /=
# %=
# //=
# **=
# &=
# |=
# ^=
# >>=
# <<=
In [7]:
x = 10
print(x)
x += 20
print(x)
10 30
In [8]:
x = 4
print(x)
x **= 2
print(x)
4 16
In [9]:
x = 4
print(x)
x &= 5
print(x)
4 4
In [36]:
x = 10
print(x)
x++
print(x)
Cell In[36], line 3 x++ ^ SyntaxError: invalid syntax
In [37]:
x = 10
print(x)
++x
print(x)
10 10
In [38]:
x = 10
print(x)
++++x
print(x)
10 10
In [39]:
x = 10
print(x)
--x
print(x)
10 10
In [40]:
x = 10
print(x)
---x
print(x)
10 10
In [41]:
x = 10
print(x)
x =+ x
print(x)
10 10
In [42]:
x = 10
print(x)
x =+ x
print(x)
x = x
print(x)
10 10 10
In [43]:
x = 10
print(x)
x =-- x
print(x)
10 10
In [44]:
x = 10
print(x)
x =--- x
print(x)
10 -10
In [45]:
# # How to handle increment and decrement in python
In [46]:
x = 10
print(x)
x = x+1
print(x)
10 11
In [47]:
x = 10
print(x)
x += 1
print(x)
10 11
In [48]:
x = 10
print(x)
x = x-1
print(x)
10 9
In [49]:
x = 10
print(x)
x -= 1
print(x)
10 9
# Ternary Operator or Conditional Operator :-¶
In [50]:
# Unary Operators :-
# ~x
# not x
In [51]:
# Binary Operators :-
# a+b
# a*b
In [52]:
# Ternary Operator or Conditional Operator :-
# a,b = 10,20
# x = 30 if a<b else 40
# x = first value if condition else second value
In [53]:
a,b = 10,20
x = 30 if a<b else 40
print(x)
30
In [59]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
min = a if a < b else b
print('Minimum Value:', min)
Minimum Value: 2
In [64]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
c = int(input('Enter Third Number: '))
min = a if a<b and a<c else b if b<c else c
print('Minimum Value:', min)
Minimum Value: 12
In [65]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
c = int(input('Enter Third Number: '))
min = a if a>b and a>c else b if b>c else c
print('Maximum Value:', min)
Minimum Value: 99
In [66]:
a = int(input('Enter First Number: '))
b = int(input('Enter Second Number: '))
s1 = 'Both Number are Equal'
s2 = 'First Number is greater than Second Number'
s3 = 'First NUmber is less than Second Number'
result = s1 if a==b else s2 if a>b else s3
print(result)
Both Number are Equal
In [67]:
max(10, 20, 50, 90, 30, 500, 450, 160, 420, 390)
Out[67]:
500
# 6. Special Operators :-¶
In [71]:
# Special Operators :-
# 1. Identity Operator
# 2. Membership Operator
In [72]:
# 1. Identity Operator
# is
# is not
# Example:
# r1 is r2 retruns True if both refrences are pointing to the same address
# r1 is not r2 retruns True if both refrences are not pointing to the same object
In [73]:
a = 10
b = 10
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
140731373110344 140731373110344 True False
In [74]:
a = 10
b = 20
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
140731373110344 140731373110664 False True
In [77]:
a = [10,20,30,40]
b = [10,20,30,40]
print(id(a))
print(id(b))
print(a is b)
print(a == b)
print(a is not b)
1772942460224 1772942011136 False True True
In [78]:
a = [10,20,30,40]
b = a
print(id(a))
print(id(b))
print(a is b)
print(a == b)
print(a is not b)
1772948496768 1772948496768 True True False
In [79]:
# 2. Membership Operator :-
# given object present in the given collection or not
# collection can be --> string, list, tuple, set, dict etc
# obj in collection ==> if obj is member of collection returns True
# not in collection ==> if obj is not member of collection returns True
In [80]:
x = 'hello learning python is very easy!!!'
In [81]:
'h' in x
Out[81]:
True
In [82]:
'd' in x
Out[82]:
False
In [83]:
'd' not in x
Out[83]:
True
In [84]:
'python' in x
Out[84]:
True
In [85]:
'python' not in x
Out[85]:
False
In [86]:
list = ['sunny', 'bunny', 'chinny', 'vinny']
In [87]:
'bunny' in list
Out[87]:
True
In [88]:
'buuny' in list
Out[88]:
False
In [89]:
10+20*3
Out[89]:
70
# Python Operator Precedence :-¶
In [91]:
# ()
# **
# ~,-(unary minus)
# *, /, %, //
# +, -
# <<, >>
# &
# ^
# |
# >, >=, <, <=, ++, !=
# =, +=, -=, *=, ...
# is, is not
# in, in not
# not
# and
# or
In [92]:
a = 30
b = 20
c = 10
d = 5
In [93]:
(a+b)*c/d
Out[93]:
100.0
In [94]:
(a+b)*(c/d)
Out[94]:
100.0
In [95]:
a+(b*c)/d
Out[95]:
70.0
In [ ]:
In [2]:
# # # Mathematical Functions by using Math Module :-
In [3]:
# Library Contains ---> a group of packages
# Package Contains ---> a group of modules
# Module Contains ---> a group of functions, variables, classes etc
In [4]:
# Module name: durgamath
# import durgamath
# short alias name
# import durgamath as dm
In [ ]:
# from durgamath as dm
# print(dm.PI)
# print(dm.name)
# dm.add(10,20)
# dm.multiply(10,20)
# s = dm.Student()
# s.activity()
In [5]:
# # Note :-
# Once we defined alias name, we cannot use original name.
In [ ]:
# from durgamath as dm
# print(durgamath.PI)
# print(dm.name)
# dm.add(10,20)
# dm.multiply(10,20)
# s = dm.Student()
# s.activity()
# It will show error
In [ ]:
# Access memebers directly without module name???
# from durgamath import PI
In [6]:
# from durgamath import PI, name
# print(PI)
# print(name)
# add(10,20)
# multiply(10,20)
# s = Student()
# s.activity()
# In this only PI and name are available
In [7]:
# from durgamath import *
# print(PI)
# print(name)
# add(10,20)
# multiply(10,20)
# s = Student()
# s.activity()
In [10]:
# Alias name for the members :-
In [9]:
# from durgamath import add as a
# a(100,200)
In [11]:
import math
In [12]:
math.sqrt(16)
Out[12]:
4.0
In [14]:
math.pi
Out[14]:
3.141592653589793
In [15]:
from math import *
In [16]:
sqrt(16)
Out[16]:
4.0
In [17]:
pi
Out[17]:
3.141592653589793
In [18]:
import math as m
In [19]:
m.sqrt(16)
Out[19]:
4.0
In [20]:
m.pi
Out[20]:
3.141592653589793
In [21]:
import math
In [23]:
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
In [25]:
from math import *
print('PI =',pi)
print('E =',e)
print(ceil(10.1))
print(floor(10.1))
PI = 3.141592653589793 E = 2.718281828459045 11 10
In [26]:
from random import randint
In [27]:
randint(0,9)
Out[27]:
5
In [28]:
randint(0,9)
Out[28]:
2
In [29]:
from random import *
In [30]:
randint(0,9)
Out[30]:
3
In [ ]:
# # Input and Output Statements :-¶
# Input Statements :-¶
In [2]:
# To read dynamic input from the keyboard :-
# 1. raw_input()
# 2. input()
In [3]:
# 1. raw_input() :-
# x = raw_input('Enter some value:')
# print(type(x)) # str type only
# i = int(x)
# Typecasting is required
In [4]:
# 2. input() :-
# x = input('Enter some value:')
# print(type(x)) # the result need not be str type
# Typecasting is not required
In [5]:
# This story is not appl only for Python-2 but not for Python-3
In [6]:
# In Python-3, we have only input() function but not raw_input() function.
# Python-3 input() function ==> Python-2 raw_input() function
# In Python-3 input() function always returns str type only.
# We have to perform typcasting.
In [7]:
# 100 objects ==> minimum 90% of objects are string type only
# 10% requirement ==> typecasting functions are there
In [8]:
x = input('Enter some value: ')
print(type(x))
<class 'str'>
In [9]:
x = int(input('Enter some value: '))
print(type(x))
<class 'int'>
In [10]:
# # String to Other Types :-
In [16]:
# Type casting functions are required
# Type casting ==> Type Conversion
# str --> int type ==> int(str)
# str --> float type ==> float(str)
# str --> boolean type ==> boolean(str)
# str --> complex type ==> complex(str)
In [19]:
x = input('Enter some value: ')
i = int(x)
print(type(i))
<class 'int'>
In [20]:
x = input('Enter some value: ')
i = float(x)
print(type(i))
<class 'float'>
In [14]:
x = input('Enter some value: ')
i = bool(x)
print(type(i))
<class 'bool'>
In [15]:
x = input('Enter some value: ')
i = complex(x)
print(type(i))
<class 'complex'>
In [21]:
x = input('Enter First Number: ')
y = input('Enter Second Number: ')
x = int(x)
y = int(y)
print('Sum is:', x+y)
Sum is: 6924
In [24]:
x = int(input('Enter First Number: '))
y = int(input('Enter Second Number: '))
print('Sum is:', x+y)
Sum is: 11
In [25]:
eno = int(input('Enter Employee Number: '))
ename = input('Enter Employee Name: ')
esal = float(input('Enter Employee Salary: '))
eaddr = input('Enter Employee Address: ')
married = bool(input('Employee Married?[True|False]: '))
print('Please Confirm your Information:')
print('Employee Number: ', eno)
print('Employee Name: ', ename)
print('Employee Salary: ', esal)
print('Employee Address: ', eaddr)
print('Employee Married: ', married)
Please Confirm your Information: Employee Number: 784 Employee Name: ankd Employee Salary: 4654.0 Employee Address: acef Employee Married: True
In [ ]:
# eval('str')
# eval('10') --> int
# eval('10.5') --> float
# eval('True') --> boolean
# eval('False') --> boolean
In [28]:
eno = int(input('Enter Employee Number: '))
ename = input('Enter Employee Name: ')
esal = float(input('Enter Employee Salary: '))
eaddr = input('Enter Employee Address: ')
married = eval(input('Employee Married?[True|False]: '))
print('Please Confirm your Information:')
print('Employee Number: ', eno)
print('Employee Name: ', ename)
print('Employee Salary: ', esal)
print('Employee Address: ', eaddr)
print('Employee Married: ', married)
Please Confirm your Information: Employee Number: 46 Employee Name: dwf Employee Salary: 45.0 Employee Address: ad Employee Married: False
In [29]:
# # eval() :-
In [30]:
# eval() functin take string as argument and evaluates the result.
In [35]:
x = eval('10+20+30')
print(x)
print(type(x))
60 <class 'int'>
In [36]:
x = int('10+20+30')
print(x)
print(type(x))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[36], line 1 ----> 1 x = int('10+20+30') 2 print(x) 3 print(type(x)) ValueError: invalid literal for int() with base 10: '10+20+30'
In [37]:
x = eval(input('Enter some Value:'))
print(x)
print(type(x))
(10, 10, 51) <class 'tuple'>
In [38]:
x = eval('true')
print(x)
print(type(x))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[38], line 1 ----> 1 x = eval('true') 2 print(x) 3 print(type(x)) File <string>:1 NameError: name 'true' is not defined
In [39]:
x = eval('True')
print(x)
print(type(x))
True <class 'bool'>
In [40]:
x = eval(input('Enter some Value:'))
print(x)
print(type(x))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[40], line 1 ----> 1 x = eval(input('Enter some Value:')) 2 print(x) 3 print(type(x)) File <string>:1 NameError: name 'true' is not defined
In [41]:
# eval() is always taking string argument only, but that string should represent non-string value internally.
In [42]:
x = eval('durga')
print(x)
print(type(x))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[42], line 1 ----> 1 x = eval('durga') 2 print(x) 3 print(type(x)) File <string>:1 NameError: name 'durga' is not defined
In [43]:
x = eval('10')
print(x)
print(type(x))
10 <class 'int'>
In [ ]:
In [4]:
# How to read multiple values from the keyboard in a single line :-
# '10 20 30' ==> a single string which contains int values with space separator
# ['10', '20', '30'] ==> list
In [7]:
s = '10 20 30'
l = s.split()
print(l)
['10', '20', '30']
In [ ]:
# string values to int type ==> int()
In [12]:
s = '10 20 30'
l = s.split()
print(l)
['10', '20', '30']
In [13]:
a, b, c = [10, 20, 30] # unpacking
print(a, b, c)
10 20 30
In [14]:
s = input('Enter two Numbers:')
print(s)
l = s.split()
print(l)
45 65 ['45', '65']
In [15]:
l = input('Enter two Numbers:').split()
print(l)
['65', '46']
In [21]:
a, b = input('Enter two Numbers:').split()
print(a)
print(b)
print(type(a))
print(type(b))
46 654 <class 'str'> <class 'str'>
In [17]:
# for each string present in this list, convert into int value
# list comprehension
In [20]:
a, b = [int(x) for x in input('Enter two Numbers:').split()]
print(a)
print(b)
print(type(a))
print(type(b))
6546 656 <class 'int'> <class 'int'>
In [22]:
a, b = [int(x) for x in input('Enter two Numbers:').split()]
print('Product of two numbers:', a*b)
Product of two numbers: 3936
In [24]:
a, b = [int(x) for x in input('Enter two Numbers:').split(',')]
print('Product of two numbers:', a*b)
Product of two numbers: 1080
In [26]:
a, b, c = [float(x) for x in input('Enter two Numbers:').split('-')]
print('Sum of Numbers:', a+b+c)
Sum of Numbers: 15.0
# Comand Line Arguments :-¶
In [28]:
# The arguments which are passing from the command prompt
# cmd line arguments are always str type only
In [29]:
# python test.py 10 20 30
# sys module
# argv --> list
# contains 4 values
# test.py 10 20 30
# argv[0] --> test.py
# argv[1] --> 10
# argv[2] --> 20
# argv[3] --> 30
In [37]:
from sys import argv\
print(len(argv))
print(argv)
print(type(argv))
2 ['c:\\Users\\pulki\\anaconda3\\envs\\Personal\\Lib\\site-packages\\ipykernel_launcher.py', '--f=c:\\Users\\pulki\\AppData\\Roaming\\jupyter\\runtime\\kernel-v2-15792Rm05Jqyd3e23.json'] <class 'list'>
In [38]:
print(argv[0])
c:\Users\pulki\anaconda3\envs\Personal\Lib\site-packages\ipykernel_launcher.py
In [39]:
for x in argv:
print(x)
c:\Users\pulki\anaconda3\envs\Personal\Lib\site-packages\ipykernel_launcher.py --f=c:\Users\pulki\AppData\Roaming\jupyter\runtime\kernel-v2-15792Rm05Jqyd3e23.json
In [41]:
# Input --> python test.py 10 20 30
# from sys import argv
# x = argv[1:] # ['10', '20', '30']
# sum = 0
# for x1 in x:
# n = int(x1)
# sum = sum + n # sum+=n
# print('The Sum:', sum)
In [ ]:
# 1. space is the separator
# we should use ""
# 2. always str type
# typecasting
# 3. out of range index
# IndexError
In [1]:
# Language Fundamentals
# Operators and Assignments
# Input and Output Statements
# Input Statements
# input()
# command line arguments
# Output Statements
# Output Statements :-¶
In [6]:
# Form-1 :-
# print()
# To print new line character(\n)
In [7]:
print()
In [8]:
print('Hi')
Hi
In [9]:
print('\n')
In [16]:
# Form-2 :-
# print('string')
# In the string we can use escape characters also
# String repeation Operator *
# One argument must be string and other argument must be int
# 'durga' * 3
# 3 * 'durga'
# String concatenation Operator also +
# Both arguments must be strings type:
# 'durga' + 'soft'
In [11]:
print('DURGA\tSOFTWARE\tSOLUTIONS')
DURGA SOFTWARE SOLUTIONS
In [12]:
print('DURGA\nSOFTWARE\nSOLUTIONS')
DURGA SOFTWARE SOLUTIONS
In [14]:
print('DURGA' * 3)
DURGADURGADURGA
In [15]:
print('DURGA' + 'SOFT')
DURGASOFT
In [17]:
print(3 + 'durga' + 3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[17], line 1 ----> 1 print(3 + 'durga' + 3) TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [18]:
print(3 * 'DURGA' + 'SOFT')
DURGADURGADURGASOFT
In [19]:
print('DURGA' + 'SOFT')
print('DURGA' , 'SOFT')
DURGASOFT DURGA SOFT
In [26]:
# Form-3 :-
# print() with sep attribute
# default value for sep attribute: space
# Other than space if you want any other, then we should use "sep" attribute
# separator
In [21]:
a,b,c = 10,20,30
print('The Values are:', a,b,c)
The Values are: 10 20 30
In [23]:
name = 'DURGA'
gf = 'SUNNY'
print('Hello', name, 'Your Girl Friend', gf, 'is too good human being')
Hello DURGA Your Girl Friend SUNNY is too good human being
In [24]:
a,b,c = 10,20,30
print(a,b,c, sep='-')
10-20-30
In [25]:
a,b,c = 10,20,30
print(a,b,c, sep='')
102030
In [28]:
# Form-4 :-
# print() with end attribute
# Other than \n if you want any other character: end attribute
# default value for end attribute: \n
In [34]:
print('Hello')
print('durga')
print('soft')
Hello durga soft
In [36]:
print('Hello', end='*')
print('durga', end=' ')
print('soft')
Hello*durga soft
In [38]:
a,b,c = 10,20,30
print(a,b,c, sep='-', end='###')
print(a,b,c, sep='-')
print('durga')
10-20-30###10-20-30 durga
In [39]:
# Form-5 :-
# print(object)
In [40]:
print(10)
10
In [41]:
print(True)
True
In [42]:
print([10,20,30])
[10, 20, 30]
In [43]:
print((10,20,30))
(10, 20, 30)
In [45]:
# Form-6 :-
# print(formatted string)
# %i --> int
# %d --> int
# %f --> float
# %s --> string type
In [46]:
# print('formatted string' %(variable list))
In [48]:
a = 10
print('a value is %i' %a)
a value is 10
In [49]:
a = 10
b = 20
c = 30
print('a value is %i b value is %i c value is %i' %(a,b,c))
a value is 10 b value is 20 c value is 30
In [50]:
a = 10
b = 20
c = 30
print('a value is %d b value is %d c value is %d' %(a,b,c))
a value is 10 b value is 20 c value is 30
In [51]:
name = 'durga'
l = [10,20,30,40]
print('hello %s... The List of items are %s' %(name, l))
hello durga... The List of items are [10, 20, 30, 40]
In [ ]:
# Form-7 :-
# print() with {}
# {} --> Replacement Operator
In [53]:
name = 'Durga'
salary = 10000
gf = 'Sunny'
In [54]:
print(f'Hello {name}, your salary is {salary}, and your Friend is {gf}')
Hello Durga, your salary is 10000, and your Friend is Sunny
In [58]:
print('Hello {x}, your salary is {y}, and your Friend is {z}'.format(x=name, y=salary, z=gf))
Hello Durga, your salary is 10000, and your Friend is Sunny
In [60]:
print('Hello {0}, your salary is {1}, and your Friend is {2}'.format(name, salary, gf))
Hello Durga, your salary is 10000, and your Friend is Sunny
In [61]:
print('Hello {0}, your salary is {1}, and your Friend is {2}'.format(salary, gf, name))
Hello 10000, your salary is Sunny, and your Friend is Durga
In [62]:
print('Hello {}, your salary is {}, and your Friend is {}'.format(name, salary, gf))
Hello Durga, your salary is 10000, and your Friend is Sunny
In [64]:
print('Hi {0} sal is {1}'.format(0='AA', 1=10000))
Cell In[64], line 1 print('Hi {0} sal is {1}'.format(0='AA', 1=10000)) ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
In [ ]:
In [1]:
# Language Fundamentals
# Operators and Assignments
# Input and Output Statements
# # Flow Control :-¶
In [2]:
# # Flow Controls Statements :-
# Conditional Statements or Selection Statements :-
# if
# if-else
# if-elif-else
# if-elif
# Iterative Statements (Loops) :-
# for
# while
# Transfer Staements :-
# break
# continue
# pass
# del
# 1. Conditional Statements :-¶
In [11]:
# 1. if :-
In [13]:
# if condition:
# body
# Indentation is important in Python
In [5]:
# if condition:
# statement
# statement
# statement
# statements
# statements
In [7]:
name = input('Enter Your Name:')
if name == 'durga':
print('Hello Durga!')
print('How are you')
Hello Durga! How are you
In [10]:
# 2. if-else :-
In [14]:
# if condition:
# action-1
# else:
# action-2
In [16]:
name = input('Enter Your Name:')
if name == 'durga':
print('Hello Durga!')
else:
print('Hello Guest!')
print('How are you')
Hello Guest! How are you
In [21]:
# 3. if-elif-else :-
In [22]:
# if condition-1:
# action-1
# elif condition-2:
# action-2
# elif condition-3:
# action-3
# elif condition-4:
# action-4
# ....
# else:
# default Action
In [23]:
brand = input('Enter Your Favourite Brand:')
if brand == 'RC':
print('RC is a great brand')
elif brand == 'KF':
print('KF is a great brand')
elif brand == 'KO':
print('KO is a great brand')
elif brand == 'FO':
print('FO is a great brand')
else:
print('I dont know that brand')
I dont know that brand
In [25]:
# 4. if-elif :-
In [27]:
# if condition-1:
# action-1
# elif condition-2:
# action-2
# elif condition-3:
# action-3
# elif condition-4:
# action-4
In [29]:
brand = input('Enter Your Favourite Brand:')
if brand == 'RC':
print('RC is a great brand')
elif brand == 'KF':
print('KF is a great brand')
elif brand == 'KO':
print('KO is a great brand')
elif brand == 'FO':
print('FO is a great brand')
print('I don\'t know brand')
I don't know brand
In [30]:
n1 = int(input('Enter First Number: '))
n2 = int(input('Enter Second Number: '))
if n1 > n2:
print(f'{n1} is greater than {n2}')
else:
print(f'{n1} is smaller than {n2}')
545 is greater than 54
In [ ]:
# 2. Iterative Statements :-¶
In [2]:
# for loop
# while loop
In [3]:
# 1. for loop :-
# for every element present in the given sequence, if we want to perform certain activity then we should go for for loop.
# for x in sequence:
# body
In [4]:
l = [10,20,30,40,50,60]
s = {10,20,30,40,50,60}
In [5]:
for x in l:
print(x)
10 20 30 40 50 60
In [10]:
x = 'durga'
for ch in x:
print('The Current Character is:',ch)
The Current Character is: d The Current Character is: u The Current Character is: r The Current Character is: g The Current Character is: a
In [12]:
s = input('Enter Any String:')
i = 0
for ch in s:
print('The Character Present at', i, 'index:', ch)
i += 1
The Character Present at 0 index: 3 The Character Present at 1 index: 4 The Character Present at 2 index: k The Character Present at 3 index: j The Character Present at 4 index: b The Character Present at 5 index: g
In [13]:
for x in range(10):
print('Hello')
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
In [14]:
for x in range(10):
print(x)
0 1 2 3 4 5 6 7 8 9
In [17]:
for x in range(1, 21):
if x%2 == 0:
print(x)
2 4 6 8 10 12 14 16 18 20
In [20]:
for x in range(10, 0, -1):
print(x)
10 9 8 7 6 5 4 3 2 1
In [ ]:
In [1]:
# To print the sum of numbers present in the given list?
In [4]:
l = eval(input('Enter List:'))
print(l)
sum = 0
for x in l:
sum += x
print('Sum is:', sum)
(10, 10, 20, 30, 40, 50) Sum is: 160
In [6]:
# while loop :-
# We don't know the number of iteration in advance, as long as some condition is True, execute body
# while condition:
# True
In [11]:
# To print numbers from 1 to 10 by using while loop?
In [12]:
x = 1
while x <= 10:
print(x)
x += 1
1 2 3 4 5 6 7 8 9 10
In [13]:
# # Note :-
# for loop is sequence based
# while loop is condition based
In [14]:
# To display the sum of first n natural numbers?
In [16]:
n = int(input('Enter n values:'))
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print('The sum of First {} Numbers: {}'.format(n, sum))
The sum of First 9 numbers: 45
In [17]:
name = ''
i = 1
while name != 'sunny' and i<=10:
name = input('Enter Name:')
print('Enter Name:', name)
i += 1
Enter Name: 454 Enter Name: SADA Enter Name: ASDSLAMF Enter Name: DSFKLER Enter Name: KVNFA Enter Name: KNAFSKASF Enter Name: FAKSNFK Enter Name: MLSNFL Enter Name: MCKEANF Enter Name: sunny
In [18]:
name = ''
i = 1
while name != 'sunny' and i<=10:
name = input('Enter Name:')
print('Enter Name:', name)
i += 1
if i == 10:
print('You entered more than 10 times. Exiting...')
break
print('Thanks for Confirmation')
Enter Name: sfew Enter Name: wgrw Enter Name: eg Enter Name: erwg Enter Name: wrgrw Enter Name: g Enter Name: gtrt Enter Name: wgw Enter Name: rg You entered more than 10 times. Exiting... Thanks for Confirmation
In [19]:
# name != 'sunny' and i<=10 ===> Returns False then only it will be stopped
# name != 'sunny' ===> If you enter name as sunny the the result is False
# i<=10 ===> If i value > 10 then it results False
In [20]:
# Infinite Loop :-
# Nested Loop :-
# Loop inside another loop
In [21]:
for i in range(4):
for j in range(4):
print(i, j)
0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 2 3 3 0 3 1 3 2 3 3
In [22]:
# read data from the end user as long as he poviding valing input
# while data is invalid:
# read data from the user
# while True:
# read data from the user
# if data is valid:
# break
In [25]:
while True:
username = input('Enter User Name:')
pwd = input('Enter Password:')
if username == 'durga' and pwd == 'sunny':
print('Login Successful')
break
else:
print('Invalid Credentials. Please try again.')
Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Invalid Credentials. Please try again. Login Successful
In [ ]:
In [4]:
n = int(input('Enter any Number:'))
for i in range(n):
print('*', end=' ')
* * * * *
In [7]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(n):
print('*', end=' ')
print()
* * * * * * * * *
In [10]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(n):
print(n, end=' ')
print()
3 3 3 3 3 3 3 3 3
In [12]:
n = int(input('Enter any Number:'))
for i in range(n):
print('A '*n)
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
In [18]:
n = int(input('Enter any Number:'))
for i in range(n):
print((str(i+1) + ' ')* n)
1 1 2 2
In [22]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row
for j in range(n): # for every column in that row
print(i+1, end=' ')
print()
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
In [21]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row
for j in range(n): # for every column in that row
print(i, end=' ')
print()
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4
In [25]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row
for j in range(n): # for every column in that row
print(chr(65+i), end=' ')
print()
A A A A A A A A A B B B B B B B B B C C C C C C C C C D D D D D D D D D E E E E E E E E E F F F F F F F F F G G G G G G G G G H H H H H H H H H I I I I I I I I I
In [ ]:
In [1]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row i = 1,2,3,4,....,n
for j in range(n): # j = 1,2,3,4,..,n
print(j+1, end=' ')
print()
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
In [4]:
n = int(input('Enter any Number:'))
for i in range(1, n+1): # for every row i = 1,2,3,4,....,n
for j in range(1, n+1): # j = 1,2,3,4,..,n
print(j+1, end=' ')
print()
2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6
In [5]:
n = int(input('Enter any Number:'))
for i in range(1, n+1): # for every row i = 1,2,3,4,....,n
for j in range(1, n+1): # j = 1,2,3,4,..,n
print(j, end=' ')
print()
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
In [13]:
n = int(input('Enter any Number:'))
for i in range(n): # for every row i = 1,2,3,4,....,n
for j in range(n): # j = 1,2,3,4,..,n
print(n-j, end=' ')
print()
5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1
In [16]:
for i in range(10, 1, -1):
print(i)
10 9 8 7 6 5 4 3 2
In [26]:
n = int(input('Enter any Number:'))
for i in range(n):
print('*' * (i+1))
* ** ***
In [30]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(i+1):
print('*', end=' ')
print()
* * * * * *
In [41]:
n = int(input('Enter any Number:'))
for i in range(n):
for j in range(i+1):
print(n-j, end=' ')
print()
5 5 4 5 4 3 5 4 3 2 5 4 3 2 1
In [57]:
n = int(input('Enter any Number:'))
for i in range(n):
print(' '*(n-i-1), end='')
print('* '*(i+1))
* * * * * * * * * * * * * * *
In [ ]:
# Transfer Statements :-¶
In [1]:
# 1. break
# 2. continue
# pass and del
# 1. break statement :-¶
In [24]:
# break loop execution based on some condition
In [4]:
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
In [6]:
for i in range(10):
print(i)
if i == 5:
print('Loop Execution enough... plz break!!')
break;
0 1 2 3 4 5 Loop Execution enough... plz break!!
In [8]:
cart = [10,20,30,40,600,50,60]
for items in cart:
if items > 500:
print('To place this order, insurance must be required')
break
print(items)
10 20 30 40 To place this order, insurance must be required
# 2. continue statement :-¶
In [ ]:
# we can use continue statement to skip current iteration and continue for the next iteration.
In [12]:
for i in range(10):
if i == 5:
continue
print(i)
0 1 2 3 4 6 7 8 9
In [14]:
for i in range(10):
if i%2 == 0:
continue
print(i)
1 3 5 7 9
In [15]:
for i in range(10):
if i%2 != 0:
continue
print(i)
0 2 4 6 8
In [16]:
cart = [10,20,30,40,600,500,60]
for item in cart:
if item >= 500:
print('We cannot process this item beacuse of insurance issue:', item)
continue
print('Processing item:', item)
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 We cannot process this item beacuse of insurance issue: 600 We cannot process this item beacuse of insurance issue: 500 Processing item: 60
In [19]:
numbers = [10,20,0,5,0,30]
for n in numbers:
if n == 0:
print('We cannot divide with 0')
continue
print('100/{} = {}'.format(n, 100/n))
100/10 = 10.0 100/20 = 5.0 We cannot divide with 0 100/5 = 20.0 We cannot divide with 0 100/30 = 3.3333333333333335
In [20]:
numbers = [10,20,0,5,0,30]
for n in numbers:
if n == 0:
print('We cannot divide with 0')
continue
print('100/{a} = {b}'.format(a=n, b=100/n))
100/10 = 10.0 100/20 = 5.0 We cannot divide with 0 100/5 = 20.0 We cannot divide with 0 100/30 = 3.3333333333333335
In [22]:
# if-else
# for-else
# while-else
# try-else-except-finally
# else block :-¶
In [35]:
# loops with else block :-
# 1. some times loop will be executed with out break
# 2. some times loop will be terminated because of break
# inside loop execution if break statement not executed, then only else part will be executed
# else means loop without break
# else is always associated with break
# without break we can use else but not that much meaningful.
In [27]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 Processing item: 50
In [28]:
cart = [10,20,30,40,500]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 we cannot place this order
In [29]:
cart = [10,20,30,40,500]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 we cannot place this order
In [30]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 Processing item: 50 Congrats!
In [33]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
continue
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 Processing item: 50 Congrats!
In [34]:
cart = [10,20,30,40,500]
for item in cart:
if item > 50:
print('we cannot place this order')
continue
print('Processing item:', item)
else:
print('Congrats!')
Processing item: 10 Processing item: 20 Processing item: 30 Processing item: 40 we cannot place this order Congrats!
In [37]:
cart = [10,20,30,40,50]
for item in cart:
if item > 50:
print('we cannot place this order')
break
print('Processing item:', item)
for i in range(2):
if i == 1:
break
print(i)
else:
print('Congrats!')
Processing item: 10 0 Processing item: 20 0 Processing item: 30 0 Processing item: 40 0 Processing item: 50 0 Congrats!
In [ ]:
In [1]:
# 1. Selection Statements/Conditional Statements :-
# if
# if-else
# if-elif
# if-elif-else
# 2. Iteration Statements (Loops) :-
# for
# while
# for-else
# while-else
# else will be executed if there is no break statement
# 3. Transfer Statements :-
# break
# continue
# # pass and del :-¶
# pass :-¶
In [12]:
# it is a keyword in python
# it is empty statement
# it is null statement
# it won't do anything
In [10]:
if 10>20:
print('Hello')
else:
Cell In[10], line 3 else: ^ SyntaxError: incomplete input
In [7]:
if 10>20:
print('Hello')
else:
pass
In [1]:
class Loan:
pass
In [2]:
class GoldLoan(Loan):
pass
In [3]:
class HomeLoan(Loan):
pass
In [4]:
class CarLoan(Loan):
pass
In [5]:
class Loan:
def getInterestRate(self):
pass
In [6]:
class GoldLoan(Loan):
def getInterestRate(self):
return 10
In [8]:
class HomeLoan(Loan):
def getInterestRate(self):
return 7
In [9]:
class CarLoan(Loan):
def getInterestRate(self):
return 13
# del :-¶
In [11]:
s1 = 'durga'
print(s1)
durga
In [12]:
s1 = 'durga'
del s1
print(s1)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[12], line 3 1 s1 = 'durga' 2 del s1 ----> 3 print(s1) NameError: name 's1' is not defined
In [13]:
s1 = 'durga'
s1 = None
print(s1)
None
In [16]:
s1 = 'durga'
print(s1)
print(s1[0])
durga d
In [18]:
del s1[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[18], line 1 ----> 1 del s1[0] TypeError: 'str' object doesn't support item deletion
In [20]:
# pass ===> empty statement
# del ===> to delete variable which are no longer required in our progream automatically the corresponding objects for gc.
# if useless objects deleted, free memory will be improved our program won't face memory issues.
In [21]:
del 'durga'
Cell In[21], line 1 del 'durga' ^ SyntaxError: cannot delete literal
In [22]:
s = 'durga'
del s
In [ ]:
# # String Data Types :-¶
In [2]:
s = 'durga'
s = 'ravi'
In [3]:
# either single quotes or double quotes
In [4]:
ch = 'a'
In [5]:
s = '''durga
software
solutions'''
print(s)
durga software solutions
In [6]:
# 1. To define multiline string literals.
# 2. To use single o rdouble quotes as symbol only.
# 3. Doc string.
In [9]:
s = '''The classes of 'Python' by "Durga Sir" are good'''
print(s)
The classes of 'Python' by "Durga Sir" are good
In [10]:
s = 'The classes of \'Python\' by \"Durga Sir\" are good'
print(s)
The classes of 'Python' by "Durga Sir" are good
In [12]:
# How to access character of the string :-
# 1. By using index
# 2. By using Slice Operator
# 1. By using index :-¶
In [17]:
# Python supports both +ve and -ve indices :-
# +ve index is always from left to right starts from 0.
# -ve index is always from right to left starts from -1.
In [19]:
s = 'durga'
print(s)
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
durga d u r g a
In [20]:
print(s[5])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[20], line 1 ----> 1 print(s[5]) IndexError: string index out of range
In [21]:
s = 'durga'
print(s)
print(s[-1])
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
durga a g r u d
In [22]:
print(s[-6])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[22], line 1 ----> 1 print(s[-6]) IndexError: string index out of range
In [24]:
# Question :-
# Write a program to read string from the keyboard and display its characters by index wise(both positive index and negative index)?
In [32]:
s = input('Enter String:')
i = 0
for x in s:
print('The Character Present at', i, 'index:', x)
i += 1
# Not correct
j = -len(s)
print(j)
for x in s[::-1]:
print('The Character Present at', j, 'index:', x)
j += 1
The Character Present at 0 index: a The Character Present at 1 index: s The Character Present at 2 index: d -3 The Character Present at -3 index: d The Character Present at -2 index: s The Character Present at -1 index: a
In [33]:
s = input('Enter any String:')
i = 0
for x in s:
print('The Character Present at Positive Index {} and at Negative Index {} is : {}'. format(i, i-len(s), x))
i += 1
The Character Present at Positive Index 0 and at Negative Index -3 is : a The Character Present at Positive Index 1 and at Negative Index -2 is : s The Character Present at Positive Index 2 and at Negative Index -1 is : d
# 2. By using Slice Operator :-¶
In [51]:
# s[begin_index:end_index:step]
# s[begin:end:step]
# s[begin_index:end_index]
# from begin_index to end_index
# begin is optional
In [36]:
s = 'Learning Python is very Easy'
In [46]:
s[:]
Out[46]:
'Learning Python is very Easy'
In [45]:
s[:7]
Out[45]:
'Learnin'
In [44]:
s[1:7]
Out[44]:
'earnin'
In [43]:
s[1:7:1]
Out[43]:
'earnin'
In [42]:
s[1:7:2]
Out[42]:
'eri'
In [47]:
s = 'abcdefghijklmnopqrstuvwxyz'
In [49]:
s[1:15:1]
Out[49]:
'bcdefghijklmno'
In [50]:
s[1:15:3]
Out[50]:
'behkn'
In [52]:
# for begin and end we can take either positive index or negative index
In [53]:
s[1:10000:1]
Out[53]:
'bcdefghijklmnopqrstuvwxyz'
In [54]:
# Slice Operator won't raise index error
In [55]:
s[11100:1000:1]
Out[55]:
''
In [56]:
s[-5:-9:-1]
Out[56]:
'vuts'
In [58]:
# steps value can be either positive or negative.
# The default step value is: +1.
# +ve step value means forward direction(left to right)
# from begin to end-1 index
# -ve step value means backward direction(right to left)
# from end to begin-1 index
In [59]:
s[::1]
Out[59]:
'abcdefghijklmnopqrstuvwxyz'
In [60]:
s[::-1]
Out[60]:
'zyxwvutsrqponmlkjihgfedcba'
In [61]:
# In Forward Direction:
# default begin value: 0
# default end value: len(s)
# default step value: +1
# In Backward Direction:
# default begin value: -1
# default end value: -len(s)+1
# default step value: -1
In [62]:
s
Out[62]:
'abcdefghijklmnopqrstuvwxyz'
In [63]:
s[::-1]
Out[63]:
'zyxwvutsrqponmlkjihgfedcba'
In [64]:
len(s)
Out[64]:
26
In [65]:
s[-1:-27:-1]
Out[65]:
'zyxwvutsrqponmlkjihgfedcba'
In [66]:
# In Forward direction if end value is 0 then result is always empty.
# In Backward direction if end value is -1 then result is always empty.
In [68]:
# s[begin:end:step]
# all attributes are optional
# all values can be either positive or negative
# if step is +ve then forward direction from begin to end-1
# if step is -ve then backward direction from begin to end+1
In [ ]:
In [1]:
s = 'abcdefghij'
In [2]:
s[1:6:2]
Out[2]:
'bdf'
In [3]:
s[3:7:-1]
Out[3]:
''
In [5]:
s[7:4:-1]
Out[5]:
'hgf'
In [6]:
s[0:10000:1]
Out[6]:
'abcdefghij'
In [7]:
s[1:10000:-1]
Out[7]:
''
In [8]:
s[-4:1:-1]
Out[8]:
'gfedc'
In [9]:
s[-4:1:-2]
Out[9]:
'gec'
In [10]:
s[5:0:1]
Out[10]:
''
In [11]:
s[9:0:0]
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[11], line 1 ----> 1 s[9:0:0] ValueError: slice step cannot be zero
In [12]:
s[0:-10:-1]
Out[12]:
''
In [13]:
s[-1:-1:-1]
Out[13]:
''
In [14]:
s[0:-2:1]
Out[14]:
'abcdefgh'
In [15]:
s[1:7:3]
Out[15]:
'be'
In [17]:
s[7:1:-3]
Out[17]:
'he'
In [20]:
s = input('Enter any string')
print('In Forward direction')
i= 0
while i< len(s):
print(s[i])
i+=1
print('In Backward direction')
i = -1
while i > -len(s)-1:
print(s[i])
i -= 1
In Forward direction 4 5 6 In Backward direction 6 5 4
In [21]:
# Membership Operator :-
# in
# not in
In [22]:
s = 'durga'
In [23]:
'a' in s
Out[23]:
True
In [24]:
'b' in s
Out[24]:
False
In [25]:
'b' not in s
Out[25]:
True
In [ ]:
In [29]:
# Number to Word Conversion :-
s = int(input('Enter the number:'))
s = s%26
num = 65 + s
word = chr(num)
print(word)
M
# Comparison of Strings :-¶
In [32]:
# >, >=, <=, <, ==
In [33]:
s1 = input('Enter First String:')
s2 = input('Enter Second String:')
if s1 == s2:
print('Both Strings are equal.')
elif s1 > s2:
print('First String is greater than Second String.')
else:
print('First String is smaller than Second String.')
Both Strings are equal.
In [36]:
city = input('Enter City:')
if city == 'Hyderabad':
print('Hello Hyderabadi...Aadaab')
elif city == 'Chennai':
print('Hello Madrasi...Vanakkam')
elif city == 'Bangalore':
print('Hello Kannadiga...Namaskaran')
else:
print('I am not familiar with', city)
I am not familiar with 456
# Remove Spaces From the Strings :-¶
In [37]:
# # Remove Spaces From the Strings :-
# rstrip ---> To remove spaces at right hand side(end of the string)
# lstrip ---> To remove spaces from left hand side(beginning of the string)
# strip ---> To remove both sides
# but it will not work on spaces b/w the words
# ex. it will not work on 'Hydera bad'
In [38]:
city = input('Enter City:').strip()
if city == 'Hyderabad':
print('Hello Hyderabadi...Aadaab')
elif city == 'Chennai':
print('Hello Madrasi...Vanakkam')
elif city == 'Bangalore':
print('Hello Kannadiga...Namaskaran')
else:
print('I am not familiar with', city)
Hello Hyderabadi...Aadaab
In [40]:
city = input('Enter City:').strip().lower()
if city == 'hyderabad':
print('Hello Hyderabadi...Aadaab')
elif city == 'chennai':
print('Hello Madrasi...Vanakkam')
elif city == 'bangalore':
print('Hello Kannadiga...Namaskaran')
else:
print('I am not familiar with', city)
I am not familiar with ghdshas
# Finding Substrings :-¶
In [42]:
# # Finding Substrings :-
# find()
# index()
# rfind()
# rindex()
In [55]:
# string.find(substring)
# Returns index of first occurrence of the given substring
# Returns -1 if it is not available
# find() will search complete string until finding the first occurrence in forward direction
In [56]:
s = 'Learning Python is very Python easy study Python'
s.find('Python')
Out[56]:
9
In [57]:
s.find('Java')
Out[57]:
-1
In [58]:
# Membership Operator :- (in and not in)
# provide True and False
# in ===> True
In [59]:
s.find('r')
Out[59]:
3
In [60]:
s.rfind('Python')
Out[60]:
42
In [64]:
# find(substring)
# find(substring, begin, end)
# from begin to end-1
In [65]:
s.find('Python', 1, 6)
Out[65]:
-1
In [66]:
s.find('Python', 1, 26)
Out[66]:
9
In [ ]:
In [1]:
s = 'Learning python is very easy'
In [2]:
s.find('p')
Out[2]:
9
In [3]:
len(s)
Out[3]:
28
In [4]:
s = 'abc'
len(s)
Out[4]:
3
In [6]:
s = 'Learning python is very easy'
s.rfind('y')
Out[6]:
27
In [16]:
# index() :-
# index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError.
In [11]:
s.find('p')
Out[11]:
9
In [12]:
s.index('p')
Out[12]:
9
In [13]:
s.find('pt')
Out[13]:
-1
In [14]:
s.index('pt')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[14], line 1 ----> 1 s.index('pt') ValueError: substring not found
In [17]:
# Program to display all positions of the substring in the given main string?
In [24]:
s = input('Enter the String:')
subs = input('Character to Find in String:')
print('String:', s)
print('Character:', subs)
count = 0
for i in s:
if i == subs:
count += 1
print(count)
String asafasdf Character a 3
In [30]:
s = input('Enter Main String:')
subs = input('Enter Sub String:')
print('Main String:', s)
print('Sub String:', subs)
n = len(s)
pos = 0
count = 0
while True:
i = s.find(subs, pos, n)
if i == -1:
print('The Total Number of Times Sub String Found:', count)
break
else:
print('Found at index:', i)
count += 1
pos = i + len(subs)
i = s.find(subs, pos, n)
Main String: asdfghjkasdfasdfgasasas Sub String: a Found at index: 0 Found at index: 8 Found at index: 12 Found at index: 17 Found at index: 19 Found at index: 21 The Total Number of Times Sub String Found: 6
# Counting Sub-String in the Given String :-¶
In [33]:
# count() method
# s.count(substring)
# s.count(substring, begin, end)
In [35]:
s = input('Enter Main String:')
subs = input('Enter Sub String:')
print('The Total Number of Times Sub String Found:', s.count(subs))
print('The Total Number of Times Sub String Found:', s.count(subs, 4, 10))
The Total Number of Times Sub String Found: 5 The Total Number of Times Sub String Found: 0
# Replacing a String with Another String :-¶
In [37]:
# ab ---> xy
# s.replace('ab', 'xy')
In [38]:
s = 'Learning Python is very difficult'
In [39]:
s1 = s.replace('difficult', 'easy')
s1
Out[39]:
'Learning Python is very easy'
In [40]:
# Write a script to remove spaces in the given string?
# strip() ---> begining and end of the string but not middle blank spaces
In [41]:
s = 'ab a b aba b a bab'
s1 = s.replace(' ', '')
s1
Out[41]:
'abababababab'
In [43]:
s = 'ab a b aba b a bab'
s1 = s.replace(' ', '')
print(len(s)-len(s1))
6
In [45]:
s = 'ab a b aba b a bab'
s
Out[45]:
'ab a b aba b a bab'
In [46]:
s1 = s.replace(' ', '')
s1
Out[46]:
'abababababab'
In [48]:
s
Out[48]:
'ab a b aba b a bab'
# Splitting of Strings :-¶
In [54]:
# s.split(separator)
In [50]:
s = 'durga software solutions'
s
Out[50]:
'durga software solutions'
In [52]:
l = s.split(' ')
l
Out[52]:
['durga', 'software', 'solutions']
In [53]:
for x in l:
print(x)
durga software solutions
In [55]:
s = '01-08-2020'
s
Out[55]:
'01-08-2020'
In [59]:
l = s.split('-')
l
Out[59]:
['01', '08', '2020']
In [62]:
type(l)
Out[62]:
list
In [60]:
for x in l:
print(x)
01 08 2020
In [61]:
s
Out[61]:
'01-08-2020'
In [63]:
s = 'hello'
s
Out[63]:
'hello'
In [64]:
s[0] = 'p'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[64], line 1 ----> 1 s[0] = 'p' TypeError: 'str' object does not support item assignment
In [ ]:
# Joining of Strings :-¶
In [2]:
# a group of strings(list or tuple) can be joined by using the the given delimiter.
# l = s.split(separator)
# s = separator.join(group of strings)
In [6]:
l = ['sunny', 'bunny', 'hunny']
l
Out[6]:
['sunny', 'bunny', 'hunny']
In [4]:
s = '-'.join(l)
s
Out[4]:
'sunny-bunny-hunny'
In [5]:
l
Out[5]:
['sunny', 'bunny', 'hunny']
In [9]:
t = ('10','20','30')
t
Out[9]:
('10', '20', '30')
In [10]:
s = '-'.join(t)
s
Out[10]:
'10-20-30'
In [11]:
s = ''.join(t)
s
Out[11]:
'102030'
In [12]:
s = ','.join(t)
s
Out[12]:
'10,20,30'
In [13]:
# split() ===> str to list
# join() ===> list/tuple to str
# Changing Case of a String :-¶
In [15]:
# 1. upper() ---> Every lower case character will be converted into upper case
# 2. lower() ---> Every upper case character will be converted into lower case
# 3. swapcase() ---> lower-->upper and upper-->lower
# 4. title() ---> First character of every word in upper case
# 5. capitalize ---> First word of it in uppercase remaing in lower
In [18]:
s = 'learning PYTHON is very easy'
s
Out[18]:
'learning PYTHON is very easy'
In [19]:
s.upper()
Out[19]:
'LEARNING PYTHON IS VERY EASY'
In [20]:
s.lower()
Out[20]:
'learning python is very easy'
In [21]:
s.swapcase()
Out[21]:
'LEARNING python IS VERY EASY'
In [22]:
s.title()
Out[22]:
'Learning Python Is Very Easy'
In [23]:
s.capitalize()
Out[23]:
'Learning python is very easy'
# To check Type of Characters Present in the Given String :-¶
In [25]:
# 1. isalnum() ---> a to z, A to Z, 0 to 9
# 2. isalpha() ---> a to z, A to Z
# 3. isdigit() ---> 0 to 9
# 4. islower() ---> If every alphabet is in lower case
# 5. isupper() ---> If every alphabet is in upper case
# 6. istitle() ---> If the string is in title case
# 7. isspace() ---> If the string contains only spaces
In [26]:
'Durga786'.isalnum()
Out[26]:
True
In [27]:
'durga786'.isalpha()
Out[27]:
False
In [28]:
'DurgA'.isalpha()
Out[28]:
True
In [29]:
'123456'.isdigit()
Out[29]:
True
In [30]:
'durga'.islower()
Out[30]:
True
In [31]:
'DURga'.islower()
Out[31]:
False
In [32]:
'durga1234'.islower()
Out[32]:
True
In [34]:
'ABC123'.isupper()
Out[34]:
True
In [35]:
'ABCd'.isupper()
Out[35]:
False
In [36]:
'Learning Python is very easy'.istitle()
Out[36]:
False
In [37]:
'Learning Python Is Very Easy'.istitle()
Out[37]:
True
In [38]:
' '.isspace()
Out[38]:
True
In [39]:
'a '.isspace()
Out[39]:
False
In [40]:
' a'.isspace()
Out[40]:
False
In [41]:
'Durga 123'.isalnum()
Out[41]:
False
In [43]:
'Dur ga'.isalpha()
Out[43]:
False
In [46]:
s = input('Enter ANY Character:')
print(s)
if s.isalnum():
print('The Character is Alphanumeric.')
if s.isalpha():
print('The Character is Alphabet.')
if s.islower():
print('The Character is Lowercase.')
else:
print('The Character is Uppercase.')
elif s.isdigit():
print('It is a digit.')
else:
print('It is a Mixed String.')
elif s.isspace():
print('It is Space Character.')
else:
print('Non Space Special Character.')
23125safsda The Character is Alphanumeric. It is a Mixed String.
# Checking Starting and Ending Part of the String :-¶
In [48]:
# s.startswith(substring)
# s.endswith(substring)
In [50]:
s = 'learning python is very easy'
s
Out[50]:
'learning python is very easy'
In [51]:
s.startswith('l')
Out[51]:
True
In [52]:
s.startswith('learning python')
Out[52]:
True
In [53]:
s.endswith('learning python')
Out[53]:
False
In [54]:
s.endswith('sy')
Out[54]:
True
In [55]:
s.endswith('very easy')
Out[55]:
True
In [ ]:
In [1]:
# # Important programs regarding string concept?
In [53]:
# Q1: Write a program to reverse the given string?
In [6]:
str = input('Enter any String:')
print('String:', str)
reverse_str = ''
for i in str[::-1]:
reverse_str = reverse_str + i
print('Reversed String:', reverse_str)
String: asd Reversed String: dsa
In [12]:
str = input('Enter any String:')
print('String:', str)
r = reversed(str)
print(type(r))
print(r)
output = ''.join(r)
print('Reversed String:', output)
String: asdg <class 'reversed'> <reversed object at 0x00000106A384AA10> Reversed String: gdsa
In [13]:
str = input('Enter any String:')
print('String:', str)
i = len(str) - 1
target = ''
while i >= 0:
target += str[i]
i -= 1
print('Reversed String:', target)
String: asd Reversed String: dsa
In [14]:
# Q2: Program to reverse order of words?
In [21]:
str = input('Enter any String:')
print('String:', str)
l = str.split()
print(l)
l1 = []
i = len(l)-1
while i >= 0:
print(l[i])
l1.append(l[i])
i -= 1
print('Reversed List:', l1)
print('Reversed Order of Words:', ' '.join(l1))
String: asad cdv vdfb ['asad', 'cdv', 'vdfb'] vdfb cdv asad Reversed String: ['vdfb', 'cdv', 'asad'] Reversed Order of Words: vdfb cdv asad
In [25]:
str = input('Enter any String:')
print('String:', str)
l = str.split()
print(l)
for i in range(len(l)):
print(l[i])
String: as cd vf ['as', 'cd', 'vf'] as cd vf
In [26]:
str = input('Enter any String:')
print('String:', str)
l = str.split()
print(l)
l1 = []
i = len(l)-1
while i >= 0:
print(l[i])
l1.append(l[i])
i -= 1
print('Reversed List:', l1)
print('Reversed Order of Words:', '-'.join(l1))
String: as df gh ['as', 'df', 'gh'] gh df as Reversed List: ['gh', 'df', 'as'] Reversed Order of Words: gh-df-as
In [28]:
# Q3: Program to reverse internal content of each word?
# input: one two three
# output: eno owt eerht
In [29]:
s = 'one two three'
print(s)
l = s.split()
print(l)
l1 = []
for x in l:
l1.append(x[::-1])
print(l1)
output = ' '.join(l1)
print(output)
one two three ['one', 'two', 'three'] ['eno', 'owt', 'eerht'] eno owt eerht
In [30]:
# Q4: Program to print cahracters at odd position and even position for the given string?
In [41]:
s = 'abcdefgh'
even = ''
odd = ''
for i in range(len(s)):
if i % 2 == 0:
even += s[i]
else:
odd += s[i]
print('Even Position Characters:', even)
print('Odd Position Characters:', odd)
Even Position Characters: aceg Odd Position Characters: bdfh
In [42]:
s = 'abcdefgh'
print('Character at even position:', s[::2])
print('Character at odd position:', s[1::2])
Character at even position: aceg Character at odd position: bdfh
In [43]:
s = 'abcdefgh'
print('Character at even Position')
i = 0
while i < len(s):
print(s[i], end=',')
i += 2
print('\nCharacter at odd Position')
i = 1
while i < len(s):
print(s[i], end=',')
i += 2
Character at even position a,c,e,g, Character at odd Position b,d,f,h,
In [44]:
s = 'abcdefgh'
even = []
odd = []
for i in range(len(s)):
if i % 2 == 0:
even.append(s[i])
else:
odd.append(s[i])
print('Even Position Characters:', even)
print('Odd Position Characters:', odd)
Even Position Characters: ['a', 'c', 'e', 'g'] Odd Position Characters: ['b', 'd', 'f', 'h']
In [46]:
# Q5: Program to merge characters of 2 strings into a single string by taking characters alternatively?
In [50]:
s1 = 'ravi'
s2 = 'teja'
output = ''
i,j = 0, 0
while i < len(s1) or j < len(s2):
output = output + s1[i] + s2[j]
i += 1
j += 1
print(output)
rtaevjia
In [51]:
s1 = 'ravikarn'
s2 = 'teja'
output = ''
i,j = 0, 0
while i < len(s1) or j < len(s2):
output = output + s1[i] + s2[j]
i += 1
j += 1
print(output)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[51], line 8 5 i,j = 0, 0 7 while i < len(s1) or j < len(s2): ----> 8 output = output + s1[i] + s2[j] 9 i += 1 10 j += 1 IndexError: string index out of range
In [52]:
s1 = 'ravikarn'
s2 = 'teja'
output = ''
i,j = 0, 0
while i < len(s1) or j < len(s2):
if i < len(s1):
output = output + s1[i]
i += 1
if j < len(s2):
output = output + s2[j]
j += 1
print(output)
rtaevjiakarn
In [ ]:
In [2]:
# Q6: Program to sort characters present in the given string. First alphabet symbols and then numeric values?
# input: B4A1D3
# output: ABD134
In [9]:
s = 'B4A1D3'
s1 = s2 = ''
for x in s:
if x.isalpha():
s1 = s1 +x
else:
s2 = s2 + x
print(s1)
print(s2)
print(sorted(s1))
print(sorted(s2))
output = ''
for x in sorted(s1):
output = output + x
for x in sorted(s2):
output = output + x
print(output)
BAD 413 ['A', 'B', 'D'] ['1', '3', '4'] ABD134
In [11]:
s = 'B4A1D3'
s1 = s2 = ''
for x in s:
if x.isalpha():
s1 = s1 +x
else:
s2 = s2 + x
print(s1)
print(s2)
print(sorted(s1))
print(sorted(s2))
output = ''.join(sorted(s1) + sorted(s2))
print(output)
BAD 413 ['A', 'B', 'D'] ['1', '3', '4'] ABD134
In [32]:
# input: a4b3c2
# output: aaaabbbcc
In [12]:
s = 'a4b3c2'
output = ''
for x in s:
if x.isalpha():
ch = x
else:
output = output + ch*int(x)
print(output)
aaaabbbcc
In [19]:
s = 'ab2cd2e2'
output = ''
ch = ''
for x in s:
if x.isalpha():
ch = ch + x
else:
output = output + ch*int(x)
ch = ''
print(output)
ababcdcdee
In [29]:
s = 'ab2cd2e2'
output = ''
num = ''
i = 0
while i < len(s):
if s[i].isalpha():
ch = s[i]
else:
num = num + s[i]
if i == len(s)-1:
output = output + ch*int(num)
if i+1 < len(s) and s[i+1].isalpha():
output = output + ch*int(num)
num = ''
i = i+1
print(output)
bbddee
In [31]:
s = 'ab10cd2e2'
output = ''
num = ''
str = ''
i = 0
while i < len(s):
if s[i].isalpha() and s[i+1].isalpha():
output = output + s[i]
elif s[i].isalpha():
ch = s[i]
else:
num = num + s[i]
if i == len(s)-1:
output = output + ch*int(num)
if i+1 < len(s) and s[i+1].isalpha():
output = output + ch*int(num)
num = ''
i = i+1
print(output)
abbbbbbbbbbcddee
In [ ]:
In [1]:
# input: a4k3b2
# output: aeknbd
In [3]:
ord('a')
Out[3]:
97
In [36]:
chr(96)
Out[36]:
'`'
In [49]:
s = 'ab24k10ba27'
output = ''
num = ''
for i in range(len(s)):
if s[i].isalpha():
ch = s[i]
output = output + ch
else:
num = num + s[i]
if i == len(s) - 1:
neword = ord(ch) + int(num)
if neword >= 123:
neword = (neword % 123) + 97
newch = chr(neword)
output = output + newch
if i+1< len(s) and s[i+1].isalpha():
neword = ord(ch) + int(num)
if neword >= 123:
neword = (neword % 123) + 97
newch = chr(neword)
output = output + newch
num = ''
print(output)
122 117 124 abzkubab
In [50]:
# Q: Program to remove duplicate characters present in the given string?
In [53]:
s = 'aaaabbbcccddd'
l = []
for i in s:
if i not in l:
l.append(i)
print(l)
''.join(l)
['a', 'b', 'c', 'd']
Out[53]:
'abcd'
In [56]:
s = input('Enter any String:')
l = []
for i in s:
if i not in l:
l.append(i)
print(l)
output = sorted(l)
output = ''.join(output)
output = output.replace(' ', '')
print(output)
['a', 's', 'd', ' ', 'm', 'e', 'j', 'v', 'f', 'n'] adefjmnsv
In [57]:
# Q: Program to find the number of occurrences of each character present in the given string?
In [59]:
d = {}
d ['a'] = 1
d['a'] = d['a']+1
print(d)
{'a': 2}
In [61]:
s = 'abcabcabbcde'
d = {}
for x in s:
if x not in d:
d[x] = 1
else:
d[x] = d[x] + 1
print(d)
for k,v in d.items():
print('{} occurs {} times'.format(k, v))
{'a': 3, 'b': 4, 'c': 3, 'd': 1, 'e': 1}
a occurs 3 times
b occurs 4 times
c occurs 3 times
d occurs 1 times
e occurs 1 times
In [ ]:
# # Collection Related DataType :-¶
In [4]:
# List
# Tuple
# Set
# Dictionary
# # List :-¶
In [3]:
# If we want to present a group of individual objects as a single entity wher insertion order preserved and duplicate objects are allowed, then we should go for list.
In [5]:
# 1. insertion order preserved
# 2. duplicate are allowed
# 3. Heterogeneous objects
# 4. It is dynamic ---> increase/decrease
# 5. mutable
# 6. indexing and slicing concepts are applicable
# 7. []
# 8. +ve and -ve index
# Creation of List Objects :-¶
In [30]:
# 1. empty list :-
In [24]:
l = []
l
Out[24]:
[]
In [31]:
# 2. if we know elements already :-
In [27]:
l = [10,20,30]
l
Out[27]:
[10, 20, 30]
In [29]:
# 3. with dynamic input :-
In [8]:
l = eval(input('enter list:'))
print(l)
print(type(l))
[10, 20, 30, 40] <class 'list'>
In [10]:
l = list(range(1,11,2))
print(l)
print(type(l))
[1, 3, 5, 7, 9] <class 'list'>
In [12]:
l = list(input('Enter String:'))
print(type(l))
print(l)
<class 'list'> ['a', 'd', 's', 's', 'a', 'f', 'd', 's']
In [18]:
# 4. list() function :-
# l = list(any other sequence)
# l = list(range(10))
In [14]:
l = list(range(1,11,3))
print(type(l))
print(l)
<class 'list'> [1, 4, 7, 10]
In [15]:
l = []
print(type(l))
print(l)
<class 'list'> []
In [16]:
l = list([10,20,30,40])
print(type(l))
print(l)
<class 'list'> [10, 20, 30, 40]
In [17]:
l = list({10,20,30,40})
print(type(l))
print(l)
<class 'list'> [40, 10, 20, 30]
In [19]:
# 5. string class split() method :-
In [21]:
s = 'Learning Python is very easy'
s
Out[21]:
'Learning Python is very easy'
In [22]:
l = s.split()
l
Out[22]:
['Learning', 'Python', 'is', 'very', 'easy']
# Accessing Elements of List :-¶
In [33]:
# by using index
# by using slice operator
In [41]:
# # by using index :-
In [35]:
l = [10,20,30,40]
l
Out[35]:
[10, 20, 30, 40]
In [36]:
l[0]
Out[36]:
10
In [37]:
l[-1]
Out[37]:
40
In [38]:
l[3]
Out[38]:
40
In [39]:
l[100]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[39], line 1 ----> 1 l[100] IndexError: list index out of range
In [40]:
# # by using slice operator :-
In [45]:
# l[begin:end:step]
# In Forward direction:
# beging to end-1
# In Backward direction:
# begin to end+1
In [44]:
l = [10,20,30,40]
l
Out[44]:
[10, 20, 30, 40]
In [46]:
l = list('abcdefghijk')
l
Out[46]:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
In [47]:
# -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
# 0 1 2 3 4 5 6 7 8 9 10
In [48]:
l[2:7:2]
Out[48]:
['c', 'e', 'g']
In [53]:
l[4::2] # from 4 to end-1 (i.e 10)
Out[53]:
['e', 'g', 'i', 'k']
In [51]:
l[8:2:-2] # from 8 to 3
Out[51]:
['i', 'g', 'e']
In [54]:
l[4:24642:2]
Out[54]:
['e', 'g', 'i', 'k']
In [56]:
# list, tuple, string ---> indexing/slicing possible
# set, dictionary ---> indexing/slicing not possible
# beacuse order is not fixed
In [64]:
# # List vs Mutability :-
In [58]:
l = [10,20,30,40]
l
Out[58]:
[10, 20, 30, 40]
In [61]:
id(l)
Out[61]:
2831139062592
In [62]:
l[0] = 777
l
Out[62]:
[777, 20, 30, 40]
In [63]:
id(l)
Out[63]:
2831139062592
# Traversing the Elements of List :-¶
In [68]:
# # Display all elements of list by using while loop :-
In [67]:
l = [10,20,30,40,50]
i = 0
while i < len(l):
print(l[i])
i += 1
10 20 30 40 50
In [69]:
l = [10,20,30,40,50]
for x in l:
print(x)
10 20 30 40 50
In [70]:
# Display only even numbers :-
In [71]:
l = [0,1,2,3,4,5,6,7,8,9,10]
for x in l:
if x % 2 == 0:
print(x)
0 2 4 6 8 10
In [72]:
# To access element on base of index use where loop
# for element base use for loop
In [74]:
l = [10,20,30,40]
i = 0
while i<len(l):
print('The element present at positive index: {} and negative index: {} is: {}'.format(i, i-len(l), l[i]))
i += 1
The element present at positive index: 0 and negative index: -4 is: 10 The element present at positive index: 1 and negative index: -3 is: 20 The element present at positive index: 2 and negative index: -2 is: 30 The element present at positive index: 3 and negative index: -1 is: 40
In [ ]:
In [9]:
# # # List Data Structure :-
# Important Functions and Methods of List :-¶
In [4]:
# functions ---> POP Concept(Procedural Oriented Programming)
# methods ---> OOP Concept(Object Oriented Programming)
In [5]:
def f1():
print('f1 function')
In [6]:
class Test:
def m1(self):
print('m1 method')
In [7]:
f1()
f1 function
In [8]:
test = Test()
test.m1()
m1 method
In [10]:
s = 'durga'
print(len(s))
print(s.upper())
5 DURGA
# 1. To get information of List :-¶
In [11]:
# 1. len() :-
# to retrun the number of elements present in the list
In [12]:
l = [10,20,30,40]
len(l)
Out[12]:
4
In [14]:
# 2. count() :-
# it returns the number of occurrences of specified element
In [15]:
l = [10,20,30,40,10,30,40,10]
l.count(10)
Out[15]:
3
In [16]:
l.count(40)
Out[16]:
2
In [17]:
l.count(50)
Out[17]:
0
In [22]:
# 3. index() :-
# it returns the index of the first occurrence of specified element
# ValueError if the element is not present in the list
# membership operator: in
In [23]:
l = [10,20,30,40,10,30,40,10]
l.index(10)
Out[23]:
0
In [24]:
l.index(40)
Out[24]:
3
In [25]:
l.index(50)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[25], line 1 ----> 1 l.index(50) ValueError: 50 is not in list
In [27]:
l = [1,2,3,1,1,1,4]
x = int(input('Enter any Element to Find Index:'))
i = l.index(x)
print('{} element first occurrence index is: {}'.format(x,i))
4 element first occurrence index is: 6
In [28]:
l = [1,2,3,1,1,1,4]
x = int(input('Enter any Element to Find Index:'))
if x in l:
i = l.index(x)
print('{} element first occurrence index is: {}'.format(x,i))
else:
print('{} element is not present in the list'.format(x))
8 element is not present in the list
# 2. Manipulating Elements of List :-¶
In [43]:
# 1. append() :-
In [41]:
l = []
l.append('A')
l.append('B')
l.append('C')
l
Out[41]:
['A', 'B', 'C']
In [42]:
l = []
for i in range(101):
if i%10 == 0:
l.append(i)
print(l)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
In [44]:
# 2. insert() :-
# To insert element ar specified index position
# If specified index is smaller than min index, then element will be inserted at beginning.
# If specified index is greater than max index, then element will be inserted at end.
In [45]:
l = [10,20,30,40,50]
l
Out[45]:
[10, 20, 30, 40, 50]
In [47]:
id(l)
Out[47]:
3050955359232
In [46]:
l.insert(1,70)
l
Out[46]:
[10, 70, 20, 30, 40, 50]
In [48]:
id(l)
Out[48]:
3050955359232
In [49]:
# l.insert(1 ,70) ---> 70 will insert at position 1
# l[1] = 70 ---> replace value at 1 with 70
In [50]:
l = [10,20,30,40,50]
l
Out[50]:
[10, 20, 30, 40, 50]
In [51]:
l.insert(-10,70)
l
Out[51]:
[70, 10, 20, 30, 40, 50]
In [52]:
l.insert(100,80)
l
Out[52]:
[70, 10, 20, 30, 40, 50, 80]
In [55]:
# # append() vs insert() :-
# append(element) ---> Element will be added in the last position
# insert(index, element) ---> Element will be added in the specified position
In [58]:
# 3. extend() :-
# l1.extend(l2)
# All elements present in l2 will be inserted to l1
In [79]:
l1 = [10,20,30,40,50]
l2 = [60,70,80]
print(l1)
print(l2)
for x in l2:
l1.append(x)
print(l1)
[10, 20, 30, 40, 50] [60, 70, 80] [10, 20, 30, 40, 50, 60, 70, 80]
In [78]:
l1 = [10,20,30,40,50]
l2 = [60,70,80]
print(l1)
print(l2)
l1.extend(l2)
print(l1)
[10, 20, 30, 40, 50] [60, 70, 80] [10, 20, 30, 40, 50, 60, 70, 80]
In [2]:
# 4. remover() :-
# remove(element)
# only first occurence
# ValueError if not present
In [12]:
l = [10,20,30,40,10,20,50]
l
Out[12]:
[10, 20, 30, 40, 10, 20, 50]
In [13]:
l.remove(10)
l
Out[13]:
[20, 30, 40, 10, 20, 50]
In [14]:
l.remove(10)
l
Out[14]:
[20, 30, 40, 20, 50]
In [15]:
l.remove(60)
l
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[15], line 1 ----> 1 l.remove(60) 2 l ValueError: list.remove(x): x not in list
In [16]:
l = [10,10,10,10,20,20,30]
x = int(input('Enter Element tot remove:'))
if x in l:
l.remove(x)
else:
print('Specified Element not avaialble')
print(l)
[10, 10, 10, 10, 20, 20]
In [18]:
l = [10,10,10,10,20,20,30]
x = int(input('Enter Element tot remove:'))
while True:
if x in l:
l.remove(x)
else:
break
print(l)
[10, 10, 10, 10, 30]
In [ ]:
In [1]:
# 5. pop() :-
# by default pop() will delete last element and returns that element.
In [2]:
l = [10,10,10,20,20,30]
print(l.pop())
print(l)
30 [10, 10, 10, 20, 20]
In [4]:
l = [10,10,10,20,20,30]
print(l.pop())
print(l.pop())
print(l.pop())
print(l)
30 20 20 [10, 10, 10]
In [5]:
l.pop()
Out[5]:
10
In [8]:
l = [10,10,10,20,20,30]
x = l.pop()
In [9]:
x
Out[9]:
30
In [16]:
l = [10,10,10]
print(l.pop())
print(l.pop())
print(l.pop())
print(l)
10 10 10 []
In [17]:
l = [10,10,10]
print(l.pop())
print(l.pop())
print(l.pop())
print(l.pop())
print(l)
10 10 10
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[17], line 6 4 print(l.pop()) 5 print(l.pop()) ----> 6 print(l.pop()) 8 print(l) IndexError: pop from empty list
In [18]:
l = [10,10,10]
print(l.pop())
print(l.pop())
print(l.pop())
if len(l) != 0:
print(l.pop())
print(l)
10 10 10 []
In [19]:
# pop() ---> last element will be deleted
# pop(index) ---> last element will be
In [28]:
l = [10,10,10,20,20,30]
print(l.pop(1))
print(l.pop(1))
print(l.pop(1))
print(l)
10 10 20 [10, 20, 30]
In [33]:
l = [10,20,30,40]
print(l)
i = 0
while i < len(l):
print(l.pop(i))
i += 1
print(l)
[10, 20, 30, 40] 10 30 [20, 40]
In [34]:
l = [10,20,30,40]
print(l)
i = 0
n = len(l)
while i < n:
print('Current index value:', i)
print('Current n value:', n)
print('The removed element:', l.pop(i))
i += 1
print(l)
[10, 20, 30, 40] Current index value: 0 Current n value: 4 The removed element: 10 Current index value: 1 Current n value: 4 The removed element: 30 Current index value: 2 Current n value: 4
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[34], line 9 7 print('Current index value:', i) 8 print('Current n value:', n) ----> 9 print('The removed element:', l.pop(i)) 11 i += 1 13 print(l) IndexError: pop index out of range
In [36]:
l = [10,20,30,40]
print(l)
while len(l) != 0:
print('The removed element:', l.pop(i))
print(l)
[10, 20, 30, 40] The removed element: 10 The removed element: 20 The removed element: 30 The removed element: 40 []
In [51]:
# # remove() vs pop() :-
# remove() :-
# element based removal
# ValueError, membership operator
# pop() :-
# index based removaland by default last element will be deleted
# IndexError
In [39]:
l = [10,20,30,40]
l
Out[39]:
[10, 20, 30, 40]
In [40]:
l.pop()
Out[40]:
40
In [41]:
l
Out[41]:
[10, 20, 30]
In [42]:
l.remove(30)
In [43]:
l
Out[43]:
[10, 20]
In [44]:
l.pop(20)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[44], line 1 ----> 1 l.pop(20) IndexError: pop index out of range
In [45]:
# pop() ---> last element will be deleted
# pop(index) ---> element will be deleted at specified index
In [ ]:
# 6. clear() :-
# to delete all elements
In [47]:
l = [10,20,30,40]
l
Out[47]:
[10, 20, 30, 40]
In [56]:
l.clear()
In [58]:
l
Out[58]:
[]
In [59]:
l = [10,20,30,40]
print(l)
print(l.clear())
print(l)
[10, 20, 30, 40] None []
In [52]:
# append()
# insert()
# extend()
# remove()
# pop()
# clear()
# Order Elements of the List :-¶
In [61]:
# 1. reverse() :-
In [62]:
l = [10,20,30,40]
print(l)
l.reverse()
print(l)
[10, 20, 30, 40] [40, 30, 20, 10]
In [64]:
# 2. sort() :-
# For numbers: Ascending order
# For strings: Alphabetic order (ASCII Based)
In [65]:
l = [10,5,15,0]
print(l)
l.sort()
print(l)
[10, 5, 15, 0] [0, 5, 10, 15]
In [66]:
l = ['sunny', 'bunny', 'vinny', 'pinny', 'chinny']
print(l)
l.sort()
print(l)
['sunny', 'bunny', 'vinny', 'pinny', 'chinny'] ['bunny', 'chinny', 'pinny', 'sunny', 'vinny']
In [67]:
l = ['sunny', 'bunny', 'vinny', 'pinny', 'chinny']
print(l)
print(l.sort())
print(l)
['sunny', 'bunny', 'vinny', 'pinny', 'chinny'] None ['bunny', 'chinny', 'pinny', 'sunny', 'vinny']
In [68]:
l = [10,5,15,0]
print(l)
print(l.sort())
print(l)
[10, 5, 15, 0] None [0, 5, 10, 15]
In [69]:
l = ['sunny', 'bunny', 10, 'pinny', 20]
print(l)
print(l.sort())
print(l)
['sunny', 'bunny', 10, 'pinny', 20]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[69], line 4 1 l = ['sunny', 'bunny', 10, 'pinny', 20] 3 print(l) ----> 4 print(l.sort()) 5 print(l) TypeError: '<' not supported between instances of 'int' and 'str'
In [70]:
l = ['sunny', 'bunny', 'vinny', 'pinny', 'chinny']
print(l)
print(l.sort(reverse=True))
print(l)
['sunny', 'bunny', 'vinny', 'pinny', 'chinny'] None ['vinny', 'sunny', 'pinny', 'chinny', 'bunny']
In [72]:
# # reverse() vs reversed() :-
# reverse() :-
# list specific method and won't return anything
# applicable only for list
# reversed() :-
# python's inbuilt function and returns reversed object
# applicable for any sequence
In [73]:
# l.sort() --->
# l.sort(reverse=True) --->
# l.sort(reverse=False) --->
# Aliasing and Cloning :-¶
In [75]:
# Aliasing :- creating duplicate reference ---> l1 = l2
# Cloning :- creating duplicate list object --->
In [82]:
# Aliasing :-
# The process of cretaing duplicate refrence variable
# l2 = l1
# Cloning :-
# The Process of creating duplicate object
# Ways to create Cloning :
# 1. By using slice operator
# 2. By using copy() method
In [83]:
# Aliasing :-
# The process of cretaing duplicate refrence variable
# l2 = l1
In [84]:
l1 = [10,20,30,40]
l2 = l1
print(l1)
print(id(l1))
print(l2)
print(id(l2))
[10, 20, 30, 40] 1435542163200 [10, 20, 30, 40] 1435542163200
In [85]:
l1[1] = 777
print(l1)
print(l2)
[10, 777, 30, 40] [10, 777, 30, 40]
In [86]:
l2[2] = 888
print(l1)
print(l2)
[10, 777, 888, 40] [10, 777, 888, 40]
In [ ]:
In [14]:
# Cloning :-
# The Process of creating duplicate object
# Ways to create Cloning :
# 1. By using slice operator
# 2. By using copy() method
In [10]:
l1 = [10,20,30,40]
l2 = l1[:]
print(l1)
print(id(l1))
print(l2)
print(id(l2))
[10, 20, 30, 40] 2546502628992 [10, 20, 30, 40] 2546502573504
In [11]:
l1[1] = 777
print(l1)
print(l2)
[10, 777, 30, 40] [10, 20, 30, 40]
In [12]:
l1 = [10,20,30,40]
l2 = l1.copy()
print(l1)
print(id(l1))
print(l2)
print(id(l2))
[10, 20, 30, 40] 2546502668224 [10, 20, 30, 40] 2546502553856
In [13]:
l1[1] = 777
print(l1)
print(l2)
[10, 777, 30, 40] [10, 20, 30, 40]
In [15]:
l1[2] = 888
print(l1)
print(l2)
[10, 777, 888, 40] [10, 20, 30, 40]
In [16]:
l2[2] = 999
print(l1)
print(l2)
[10, 777, 888, 40] [10, 20, 999, 40]
# Mathematical Operators for List Object :-¶
In [19]:
# + operator
In [20]:
a = [10,20,30]
b = [40,50,60]
c = a + b
print(c)
[10, 20, 30, 40, 50, 60]
In [21]:
a = [10,20,30]
b = [40,50,60]
c = a + 40
print(c)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[21], line 3 1 a = [10,20,30] 2 b = [40,50,60] ----> 3 c = a + 40 5 print(c) TypeError: can only concatenate list (not "int") to list
In [22]:
a = [10,20,30]
b = [40,50,60]
c = a + [40]
print(c)
[10, 20, 30, 40]
In [24]:
# + operator and extend()
# + operator :-
# both should be list
# list+list
# new object will be created and returns that object
# extend() :-
# one should be list and other can be anything
# l1.extend(l2)
# new object won't be created and to the existing object only elements will be be added
In [28]:
a = [10,20,30] + [40,50,60]
print(c)
[10, 20, 30, 40]
In [29]:
a = [10,20,30]
a.extend({'a', 'b', 'c'})
print(a)
[10, 20, 30, 'a', 'c', 'b']
In [30]:
a = [10,20,30]
b = {'a', 'b', 'c'}
c = a + b
print(c)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[30], line 4 1 a = [10,20,30] 2 b = {'a', 'b', 'c'} ----> 4 c = a + b 5 print(c) TypeError: can only concatenate list (not "set") to list
In [31]:
# * operator :-
In [32]:
x = [10,20,30]
y = x*3
print(y)
[10, 20, 30, 10, 20, 30, 10, 20, 30]
In [34]:
# equality operators(==, !=) :-
# l1 and l2
# l1 == l2 returns True
# 1. The number of elements
# 2. The order of elements
# 3. The content of the elements(including case)
In [35]:
x = ['dog', 'cat', 'rat']
y = ['dog', 'cat', 'rat']
z = ['DOG', 'CAT', 'RAT']
In [36]:
x == y
Out[36]:
True
In [37]:
x == z
Out[37]:
False
In [38]:
x != z
Out[38]:
True
In [45]:
# Comparison Operators :-
# <, >, <=, >=
# Comparison is always based on first element if first element is same then go for second element
In [46]:
x = [10,10,5]
y = [10,20,30,40,50,60]
In [47]:
x > y
Out[47]:
False
In [48]:
x >= y
Out[48]:
False
In [49]:
x < y
Out[49]:
True
In [50]:
x <= y
Out[50]:
True
In [56]:
x = ['dog', 'cat', 'rat']
y = ['dog', 'cat', 'dog']
In [57]:
x > y
Out[57]:
True
In [58]:
x >= y
Out[58]:
True
In [59]:
x < y
Out[59]:
False
In [55]:
x <= y
Out[55]:
True
In [60]:
# Membership Operators :-
# in, not in
In [61]:
x = ['dog', 'cat', 'rat']
In [62]:
'dog' in x
Out[62]:
True
In [63]:
'zebra' in x
Out[63]:
False
In [64]:
'zebra' not in x
Out[64]:
True
# Nested Lists :-¶
In [66]:
# List inside List
In [67]:
l = [10,20,[30,40]]
l
Out[67]:
[10, 20, [30, 40]]
In [68]:
l[0]
Out[68]:
10
In [69]:
l[1]
Out[69]:
20
In [70]:
l[2]
Out[70]:
[30, 40]
In [72]:
l[2][0]
Out[72]:
30
In [73]:
l[2][1]
Out[73]:
40
In [74]:
l = [10,[20,[30,[40]]]]
l
Out[74]:
[10, [20, [30, [40]]]]
In [75]:
l[1][0]
Out[75]:
20
In [77]:
l[1][1]
Out[77]:
[30, [40]]
In [78]:
l[1][1][0]
Out[78]:
30
In [79]:
l[1][1][1]
Out[79]:
[40]
In [85]:
l = [[10,20,30],[40,50,60],[70,80,90]]
print(l)
print('Elements by Row Wise:')
for x in l:
print(x)
print('Elements by Matrix Style:')
for row in l:
for element in row:
print(element, end=' ')
print()
print('Elements by Matrix Style:')
for i in range(len(l)):
for j in range(len(l[i])):
print(l[i][j], end=' ')
print()
[[10, 20, 30], [40, 50, 60], [70, 80, 90]] Elements by Row Wise: [10, 20, 30] [40, 50, 60] [70, 80, 90] Elements by Matrix Style: 10 20 30 40 50 60 70 80 90 Elements by Matrix Style: 10 20 30 40 50 60 70 80 90
# List Comprehension :-¶
In [2]:
# # List Comprehension :-
# It is very easy and compact way of creating list objects from iterable object(like list, tuple, set, dictionary, range, etc) based on some condition.
# l = [ expression for item in sequence ]
# l = [ x for x in range(15) ]
# l = [ expression for item in sequence if condition ]
# l = [ 2*item for item in range(1,11) if item%2 == 0 ]
In [88]:
range(10)
Out[88]:
range(0, 10)
In [91]:
l = [x for x in range(15)]
l
Out[91]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
In [93]:
l = [item for item in range(10)]
l
Out[93]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [94]:
l = [item*item for item in range(10)]
l
Out[94]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [95]:
l = [2*item for item in range(10)]
l
Out[95]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [96]:
l = [2*item for item in range(1,11)]
l
Out[96]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [97]:
l = [2*item for item in range(1,11) if item%2==0]
l
Out[97]:
[4, 8, 12, 16, 20]
In [100]:
l = [item*item*item for item in range(1,20) if item*item*item%2==0]
l
Out[100]:
[8, 64, 216, 512, 1000, 1728, 2744, 4096, 5832]
In [104]:
l = [int(x) for x in input('Enter Multiple Values:').split()]
l
Out[104]:
[1, 2, 54, 13, 4, 54, 31, 6, 45]
In [ ]:
In [2]:
# Create a lsit with squares of first 10 natural numbers
In [5]:
l = []
for x in range(1,11):
l.append(x*x)
print(l)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [6]:
l = [x*x for x in range(1, 11)]
print(l)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [7]:
print([x*x for x in range(1, 11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [8]:
# Create a lsit with squares of first 20 even natural numbers
In [9]:
l = []
for x in range(1, 21):
if x % 2 == 0:
l.append(x*x)
print(l)
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
In [12]:
l = [ x*x for x in range(1, 21) if x*x % 2 == 0 ]
print(l)
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
In [15]:
l = [ x**2 for x in range(1, 21) if x**2 % 2 == 0 ]
print(l)
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
In [17]:
words = ['Balaiah', 'Nag', 'Venkatesh', 'Chiranjeevi']
l = [ word[0] for word in words]
print(l)
['B', 'N', 'V', 'C']
In [20]:
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
# create a list with numbers which are present in num1 but not in num2
num3 = []
for n in num1:
if n not in num2:
num3.append(n)
print(num3)
[10, 20]
In [19]:
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
# create a list with numbers which are present in num1 but not in num2
num3 = [ x for x in num1 if x not in num2 ]
print(num3)
[10, 20]
In [21]:
num1 = [10, 20, 30, 40]
num2 = [30, 40, 50, 60]
# create a list with common numbers which are present in both lists
num3 = [ x for x in num1 if x in num2 ]
print(num3)
[30, 40]
In [22]:
s = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
words = s.split()
print(words)
['THE', 'QUICK', 'BROWN', 'FOX', 'JUMPS', 'OVER', 'THE', 'LAZY', 'DOG']
In [24]:
l = []
for word in words:
l.append([word, len(word)])
print(l)
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
In [25]:
l = [ [word, len(word)] for word in words]
print(l)
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
In [28]:
s = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
In [29]:
l = [ [word, len(word)] for word in s.split()]
print(l)
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]
In [30]:
l = [ [word.lower(), len(word)] for word in s.split()]
print(l)
[['the', 3], ['quick', 5], ['brown', 5], ['fox', 3], ['jumps', 5], ['over', 4], ['the', 3], ['lazy', 4], ['dog', 3]]
In [31]:
l = [ [word.capitalize(), len(word)] for word in s.split()]
print(l)
[['The', 3], ['Quick', 5], ['Brown', 5], ['Fox', 3], ['Jumps', 5], ['Over', 4], ['The', 3], ['Lazy', 4], ['Dog', 3]]
In [32]:
l = [ [word.title(), len(word)] for word in s.split()]
print(l)
[['The', 3], ['Quick', 5], ['Brown', 5], ['Fox', 3], ['Jumps', 5], ['Over', 4], ['The', 3], ['Lazy', 4], ['Dog', 3]]
In [33]:
# Program to display unique vowels present in the given word?
# Example-> 'DURGA'
In [34]:
word = input('Enter any word to Search for vowels:')
print(word)
vowels = ['a', 'e', 'i', 'o', 'u']
found = []
for v in vowels:
if v in word:
found.append(v)
print('Unique Vowels Present:', found)
adasfasdfaadsa Unique Vowels Present: ['a']
In [36]:
word = input('Enter any word to Search for vowels:')
print(word)
found = [ v for v in vowels if v in word]
print('Unique Vowels Present:', found)
aeiojaksdkbvadksfa Unique Vowels Present: ['a', 'e', 'i', 'o']
In [42]:
l =[1,2,3]
In [43]:
l.extend(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[43], line 1 ----> 1 l.extend(10) TypeError: 'int' object is not iterable
In [44]:
l.extend('durga')
print(l)
[1, 2, 3, 'd', 'u', 'r', 'g', 'a']
In [ ]:
# # Tuple Data Structure :-¶
In [16]:
# 1. It is exactly same as list exvcept thta it is immutable.
# Once we creates tuple object, we cannot change its content.
# It is read only version of list.
# 2. Duplicates are allowed
# 3. Order will be preserved
# 4. index and slicing concepts are applicable
# 5. heterogeneous objects area allowed
# 6. ()
# 7. parenthesis are optional
# single valued tuple ===> , is manadatory
In [3]:
l = [10, 20, 30, 40]
print(l)
l[0] = 777
print(l)
[10, 20, 30, 40] [777, 20, 30, 40]
In [4]:
t = (10, 20, 30, 40)
print(t)
(10, 20, 30, 40)
In [5]:
t[0] = 777
print(t)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[5], line 1 ----> 1 t[0] = 777 2 print(t) TypeError: 'tuple' object does not support item assignment
In [ ]:
In [6]:
t = (10, 20, 10, 'durga', '40')
t
Out[6]:
(10, 20, 10, 'durga', '40')
In [7]:
t[0]
Out[7]:
10
In [8]:
t[1:4]
Out[8]:
(20, 10, 'durga')
In [13]:
t = 10,20,30,40
type(t)
Out[13]:
tuple
In [12]:
t = 10,
type(t)
Out[12]:
tuple
In [14]:
t = (10)
type(t)
Out[14]:
int
In [15]:
t = (10,)
type(t)
Out[15]:
tuple
In [17]:
t = ()
type(t)
Out[17]:
tuple
In [ ]:
In [2]:
# list is mutable where as tuple is immutable
# facebook/ youtube comments section ---> List
# vendor machines ---> The allowed inputs are always fixed ---> tuple
# Bank Application
# account_types: Savings, Current ---> tuple
# Deposit machines..... like Notes are fixed(100, 200, 500, 2000)
In [4]:
# list ---> to access element l[10] ---> 10ns
# tuple ---> to access element t[10] ---> 6ns
# 100 elements ---> list ---> 100Bytes
# 100 elements ---> tuple ---> 60Bytes
In [9]:
import sys
l = [10, 20, 30, 40, 50, 60, 70, 80, 90]
t = (10, 20, 30, 40, 50, 60, 70, 80, 90)
print(sys.getsizeof(l))
print(sys.getsizeof(t))
136 112
In [5]:
# A sequence of elements
# order is important
# duplicates are allowed
In [6]:
# # Tuple Creation :-
In [7]:
t = ()
type(t)
Out[7]:
tuple
In [8]:
# list ---> tuple
# set ---> tuple
# By Using tuple() Function :-¶
In [12]:
l = [10, 20, 30]
print(l)
t = tuple(l)
print(t)
[10, 20, 30] (10, 20, 30)
In [13]:
r = range(10)
t = tuple(r)
print(t)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
In [16]:
# eval() :-
In [14]:
t = eval(input('Enter tuple Value:'))
print(type(t))
print(t)
<class 'tuple'> (4164564, 121, 54)
In [15]:
l = eval(input('Enter List Value:'))
print(type(l))
print(l)
<class 'tuple'> (54, 5415, 5465, 415)
In [17]:
# # Accessing Elements of Tuple :-
In [21]:
# by using index
# by using slice opeartor
In [22]:
t = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
t
Out[22]:
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
In [23]:
t[0]
Out[23]:
10
In [24]:
t[5]
Out[24]:
60
In [25]:
t[1:8:2]
Out[25]:
(20, 40, 60, 80)
# Tuple vs Immutable :-¶
In [27]:
# Tuples are immutable
In [28]:
t = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
t
Out[28]:
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
In [29]:
t[0] = 777
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[29], line 1 ----> 1 t[0] = 777 TypeError: 'tuple' object does not support item assignment
# Mathematical Operators :-¶
In [67]:
# +, *, ==, !=, >, >=, <, <=
In [58]:
t1 = (10, 20, 30)
t2 = (40, 50, 60)
print(t1)
print(t2)
(10, 20, 30) (40, 50, 60)
In [59]:
t3 = t1 + t2
print(t3)
(10, 20, 30, 40, 50, 60)
In [60]:
t4 = t1 * 3
print(t4)
(10, 20, 30, 10, 20, 30, 10, 20, 30)
# Important Functions and method related to Tuple :-¶
In [61]:
# 1. len()
# 2. count()
# 3. index()
# 4. sorted()
# 5. min()
# 6. max()
In [62]:
t = (10, 20, 30)
len(t)
Out[62]:
3
In [63]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.count(10)
Out[63]:
3
In [64]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.index(10)
Out[64]:
0
In [65]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.index(40)
Out[65]:
3
In [66]:
t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10)
t1.index(52)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[66], line 2 1 t1 = (10, 20, 30, 40, 50, 60, 10, 40, 10) ----> 2 t1.index(52) ValueError: tuple.index(x): x not in tuple
In [50]:
l = [0, 20, 5, 15, 10]
l.sort()
print(l)
[0, 5, 10, 15, 20]
In [51]:
t = (0, 20, 5, 15, 10)
t.sort()
print(t)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[51], line 2 1 t = (0, 20, 5, 15, 10) ----> 2 t.sort() 3 print(t) AttributeError: 'tuple' object has no attribute 'sort'
In [53]:
t = (0, 20, 5, 15, 10)
l1 = tuple(sorted(t))
print(l1)
(0, 5, 10, 15, 20)
In [54]:
t = (0, 20, 5, 15, 10)
l1 = tuple(sorted(t, reverse=True))
print(l1)
(20, 15, 10, 5, 0)
In [55]:
t = (0, 20, 5, 15, 10)
print(t)
print(min(t))
(0, 20, 5, 15, 10) 0
In [56]:
t = (0, 20, 5, 15, 10)
print(t)
print(max(t))
(0, 20, 5, 15, 10) 20
# sort() vs sorted() :-¶
In [72]:
# sort() is list specific method.
# Applicable only for list
# It won't create new list and in the existing list only sorting will be happening
# return type ---> None
# sorted() is general purpose python's inbuilt function.
# Applicable for any sequence
# A new lsit object will be created always
# return type ---> List
In [71]:
l = [0, 20, 5, 15, 10]
print("Before Sorting:", l)
print("Before Sorting Address:", id(l))
l.sort()
print("After Sorting:", l)
print("After Sorting Address:", id(l))
Before Sorting: [0, 20, 5, 15, 10] Before Sorting Address: 1986209712704 After Sorting: [0, 5, 10, 15, 20] After Sorting Address: 1986209712704
In [70]:
l = [0, 20, 5, 15, 10]
print("Before Sorting:", l)
print("Before Sorting Address:", id(l))
l1 = sorted(l)
print("After Sorting:", l1)
print("After Sorting Address:", id(l1))
Before Sorting: [0, 20, 5, 15, 10] Before Sorting Address: 1986209665280 After Sorting: [0, 5, 10, 15, 20] After Sorting Address: 1986209667392
In [73]:
print(l)
[0, 5, 10, 15, 20]
In [75]:
t1 = (10, 20, 30, 40)
t2 = (10, 20, 30, 40)
t3 = (20, 30, 40, 10)
print(t1)
print(t2)
print(t3)
(10, 20, 30, 40) (10, 20, 30, 40) (20, 30, 40, 10)
In [76]:
t1 == t2
Out[76]:
True
In [77]:
t1 == t3
Out[77]:
False
In [78]:
t1 != t3
Out[78]:
True
In [79]:
t1 < t2
Out[79]:
False
In [80]:
t1 < t3
Out[80]:
True
# Tuple Packing and Unpacking :-¶
In [86]:
# Tuple Packing :-
# t = a, b, c, d ===> pack 4 values into a single tuple
# Tuple Unpacking :-
# a, b, c, d = t ===> unpack 4 values from a tuple t and assign to a, b, c, d
In [83]:
a = 10
b = 20
c = 30
d = 40
t = a, b, c, d
print(t)
(10, 20, 30, 40)
In [85]:
t = (10, 20, 30, 40)
a, b, c, d = t
print(a, b, c, d)
10 20 30 40
In [87]:
t = (10, 20, 30, 40)
a, b, c, d, e = t
print(a, b, c, d, e)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[87], line 2 1 t = (10, 20, 30, 40) ----> 2 a, b, c, d, e = t 3 print(a, b, c, d, e) ValueError: not enough values to unpack (expected 5, got 4)
In [88]:
t = (10, 20, 30, 40)
a, b, c = t
print(a, b, c)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[88], line 2 1 t = (10, 20, 30, 40) ----> 2 a, b, c = t 3 print(a, b, c) ValueError: too many values to unpack (expected 3)
In [89]:
# *c ---> a group of values(tuple)
# **c ---> a group of key-value pairs(dictionary)
In [92]:
t = (10, 20, 30, 40, 50, 60, 70)
a, b, *c = t
print(a)
print(b)
print(c)
10 20 [30, 40, 50, 60, 70]
In [93]:
# *args ---> variable mumber of arguments
# **kwargs ---> variable mumber of keyword arguments
In [94]:
l = [x * x for x in range(1, 6)]
print(type(l))
print(l)
<class 'list'> [1, 4, 9, 16, 25]
In [95]:
t = (x * x for x in range(1, 6))
print(type(t))
print(t)
<class 'generator'> <generator object <genexpr> at 0x000001CE735B45F0>
# Difference b/w List and Tuple :-¶
In [101]:
# # List :-
# List is
# [10, 20, 30, 40]
# 1. Mutable
# 2. performance wise, memory wise list is not up to the mark
# 3. comprehension concept --> list
# 4. packing
# 5. List object --> non hashable/ unhashable object
# We cannot use as key in dictionary
# # Tuple :-
# Tuple is
# (10, 20, 30, 40) or 10, 20, 30, 40
# 1. Immutable
# 2. performance wise, memory wise tuple is up to the mark
# 3. comprehension concept --> not applicable
# 4. packing and unpacking
# 5. Tuple object --> hashable object
# We can use as key in dictionary
In [102]:
d = {[10, 20, 30, 40]: "durga"}
print(d)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[102], line 1 ----> 1 d = {[10, 20, 30, 40]: "durga"} 2 print(d) TypeError: unhashable type: 'list'
In [103]:
d = {(10, 20, 30, 40): "durga"}
print(d)
{(10, 20, 30, 40): 'durga'}
In [104]:
# WAP to take tuple numbers from keyboard and print ist sum and average?
In [107]:
t = eval(input("Enter Tuple Numbers:"))
print(t)
l = len(t)
sum = 0
for n in t:
sum = sum + n
print("Sum:", sum)
print('Average:',sum/l)
(1321, 63156, 43654, 63465) Sum: 171596 Average: 42899.0
In [ ]:
In [1]:
# List
# Tuple
# Order will be preserved
# Duplicates are allowed
# # Set Data Structure :-¶
In [3]:
# Order is not important
# Duplicates objects are not allowed i.e. we required to hold only unique objects.
In [4]:
# sms message.about duragasoftonline.com courses offer.
# 1 lakh mobile numbers
# duplicates are not allowed ---> we use set
In [7]:
# # Set Properties :-
# Order is not Preserved.
# indexing and slicing concepts are not applicable.
# Duplicates Objects are not allowed.
# heterogeneous objects are allowed.
# mutable and growable
# by using {} we can represent set of elements
# mathematical operations like union, intersection, difference etc.
In [9]:
s = {10, "durag", 30}
s
Out[9]:
{10, 30, 'durag'}
In [10]:
s = {10, "durag", 30, 10, 10, 20}
s
Out[10]:
{10, 20, 30, 'durag'}
# Creation of Set Objects :-¶
In [24]:
# 1. s = {10, 20, 30, 40}
# 2. s = set(any sequence)
# s = set(list)
# s = set(range)
# 3. By using eval()
In [12]:
s = {10, 20, 30, 40}
s
Out[12]:
{10, 20, 30, 40}
In [15]:
s = {20, 40, 30, 10}
s
Out[15]:
{10, 20, 30, 40}
In [16]:
l = [20, 10, 30, 10, 50, 10, 10, 40]
s = set(l)
print(s)
{40, 10, 50, 20, 30}
In [17]:
l = (20, 10, 30, 10, 50, 10, 10, 40)
s = set(l)
print(s)
{40, 10, 50, 20, 30}
In [18]:
s = set(range(10))
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
In [19]:
d = {100: "durga", 200: "ravi"}
s = set(d)
print(s)
{200, 100}
In [20]:
s = set('mississippi')
print(s)
{'s', 'i', 'p', 'm'}
In [23]:
s = eval(input('Any set of Elements:'))
print(s)
print(type(s))
{546, 3435, 46, 63463}
<class 'set'>
In [25]:
# # Empty set Objects :-
In [27]:
# s = {} ===> dict but not set
In [28]:
s = {}
type(s)
Out[28]:
dict
In [29]:
s = set()
type(s)
Out[29]:
set
# Important Methods and Functions related to Set :-¶
In [33]:
# 1. s.add(x) ---> To add an element to the set
# 2. s.update(x, y, z)
# To add multiple items to the set
# x, y, z are not individual objects, must be sequences
In [34]:
s = set()
print(s)
s.add(70)
s.add(50)
s.add(90)
s.add('ram')
s.add(50)
print(s)
set()
{50, 90, 70, 'ram'}
In [35]:
s = set()
s.update(range(1, 6))
print(s)
{1, 2, 3, 4, 5}
In [36]:
s = set()
s.update(range(1, 6), range(6, 11), "durga", "solutions")
print(s)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'r', 'd', 'n', 'l', 's', 'u', 'g', 'a', 'i', 't', 'o'}
In [39]:
s = set()
s.update(10)
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[39], line 2 1 s = set() ----> 2 s.update(10) 3 s TypeError: 'int' object is not iterable
In [40]:
s = set()
s.update('10')
s
Out[40]:
{'0', '1'}
# add() vs update() :-¶
In [42]:
# add() ---> to add single item
# update() ---> to add multiple items from the given sequence
In [43]:
s = set('mississippi')
s
Out[43]:
{'i', 'm', 'p', 's'}
In [44]:
s = set()
s.update(10,)
print(s)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[44], line 2 1 s = set() ----> 2 s.update(10,) 3 print(s) TypeError: 'int' object is not iterable
In [45]:
s = set()
s.update((10,))
print(s)
{10}
In [48]:
s = set()
s
Out[48]:
set()
In [49]:
s.add(10)
s
Out[49]:
{10}
In [50]:
s.add(10, 20, 30)
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[50], line 1 ----> 1 s.add(10, 20, 30) 2 s TypeError: set.add() takes exactly one argument (3 given)
In [51]:
s.update(10)
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[51], line 1 ----> 1 s.update(10) 2 s TypeError: 'int' object is not iterable
In [52]:
s.update(range(1, 11), range(11, 20))
s
Out[52]:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
In [54]:
s.add(range(1, 10))
s
Out[54]:
{1,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
2,
3,
4,
5,
6,
7,
8,
9,
range(1, 10)}
In [55]:
# In set every element should be hashable.
In [56]:
# List is not hashable but tuple is hashable
In [57]:
s = set()
s.add([10, 20, 30])
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[57], line 2 1 s = set() ----> 2 s.add([10, 20, 30]) 3 s TypeError: unhashable type: 'list'
In [58]:
s = set()
s.add((10, 20, 30))
s
Out[58]:
{(10, 20, 30)}
In [59]:
s = set()
s.add(range(0, 9))
s
Out[59]:
{range(0, 9)}
In [60]:
s = set()
s.update(range(0, 9))
s
Out[60]:
{0, 1, 2, 3, 4, 5, 6, 7, 8}
In [61]:
l = [10,20,30]
print(l)
l.append(40)
print(l)
l.insert(1, 50)
print(l)
[10, 20, 30] [10, 20, 30, 40] [10, 50, 20, 30, 40]
In [62]:
s.add(10)
# Internally PVM will store elements of set based on hashing.
# str is hashable type
# int is hashable type
# list is not hashable
In [63]:
s = set()
s.add(10)
s
Out[63]:
{10}
In [64]:
s = set()
s.add(10.5)
s
Out[64]:
{10.5}
In [65]:
s = set()
s.add("durga")
s
Out[65]:
{'durga'}
In [66]:
s = set()
s.add([10, 20, 30])
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[66], line 2 1 s = set() ----> 2 s.add([10, 20, 30]) 3 s TypeError: unhashable type: 'list'
In [67]:
s = set()
s.add((10, 20, 30))
s
Out[67]:
{(10, 20, 30)}
In [68]:
# If our frequent operation is search then set is the best choice.
In [69]:
# s = set(list) ---> in this we won;t get any error because we are not adding list object directly, we are adding elements present in the list.
# s.update(list) ---> in this we won;t get any error because we are not adding list object directly, we are adding elements present in the list.
# s.add(list) ---> we are getting error becuase we are adding list object directly to the set.
In [70]:
s = set()
s.add([10, 20, 30]) # we are adding list object to the set
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[70], line 2 1 s = set() ----> 2 s.add([10, 20, 30]) 3 s TypeError: unhashable type: 'list'
In [71]:
s = set()
s.update([10, 20, 30]) # we are adding elements present in the list to the set
s
Out[71]:
{10, 20, 30}
In [72]:
s = set([10, 20, 30])
s
Out[72]:
{10, 20, 30}
In [73]:
s = set()
s.update([10, 20, [30, 40]])
s
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[73], line 2 1 s = set() ----> 2 s.update([10, 20, [30, 40]]) 3 s TypeError: unhashable type: 'list'
In [74]:
# 3. remove() elements :-
In [75]:
# s.pop() ---> it removes and returns some random element from the set
In [81]:
s = {10, 50, 40, 20, 5, 0, 5}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
{0, 50, 20, 5, 40, 10}
0
50
20
5
40
In [83]:
s = {10, 50, 40, 20, 5, 0, 5}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
{0, 50, 20, 5, 40, 10}
0
50
20
5
40
10
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[83], line 10 8 print(s.pop()) 9 print(s.pop()) ---> 10 print(s.pop()) KeyError: 'pop from an empty set'
In [84]:
s = {10, 50, 40, 20, 5, 0, 5}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
if len(s) != 0:
print(s.pop())
{0, 50, 20, 5, 40, 10}
0
50
20
5
40
10
In [87]:
s = {10, 20, 30, 10, 20, 30, 40, 50, 60, 70, 80, 10, 20, 30, 40, 50}
while len(s) != 0:
n = s.pop()
print("Sending SMS to Mobile Number:", n)
Sending SMS to Mobile Number: 70 Sending SMS to Mobile Number: 40 Sending SMS to Mobile Number: 10 Sending SMS to Mobile Number: 80 Sending SMS to Mobile Number: 50 Sending SMS to Mobile Number: 20 Sending SMS to Mobile Number: 60 Sending SMS to Mobile Number: 30
In [93]:
# 4. remove(x) :-
# It removes the specified element
# If the specified element is not available then we will get KeyError
In [90]:
s = {10, 20, 30}
s.remove(20)
print(s)
{10, 30}
In [91]:
s = {10, 20, 30}
s.remove(40)
print(s)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[91], line 2 1 s = {10, 20, 30} ----> 2 s.remove(40) 3 print(s) KeyError: 40
In [92]:
s = {10, 20, 30}
if 40 in s:
s.remove(40)
print(s)
{10, 20, 30}
In [94]:
# 5. s.discard(x) :-
# It removes the specified element
# If the specified element is not available then we won't get any Error.
In [95]:
s = {10, 20, 30}
s.discard(40)
print(s)
{10, 20, 30}
In [96]:
s = {10, 20, 30}
s.discard(40)
s.discard(20)
s.discard(90)
s.discard(70)
s.discard(30)
print(s)
{10}
In [98]:
# remove(x) and discard(x) and pop() :-
In [99]:
# 6. s.clear() :-
# To remove all elements from the set
In [100]:
s = {10, 20, 50, 560, 54, 40, 30}
print(s)
s.clear()
print(s)
{560, 50, 20, 54, 40, 10, 30}
set()
In [101]:
# s1 = s ===> aliasing duplicate reference variable creation
# s1 = s.copy() ===> cloning duplicate set object creation
In [102]:
s = {10, 20, 30}
s1 = s
print(id(s))
print(id(s1))
2551548162144 2551548162144
In [103]:
s = {10, 20, 30}
s1 = s.copy()
print(id(s))
print(id(s1))
2551548164160 2551548159456
In [ ]:
# Mathematical Operations on the Set :-¶
In [7]:
# 1. union() ---> A | B
# 2. intersection() ---> A & B
# 3. difference() ---> A - B
# 4. symmetric_difference() ---> A ^ B
In [2]:
s1 = {1, 2, 3}
s2 = {4, 5, 6}
print(s1)
print(s2)
{1, 2, 3}
{4, 5, 6}
In [3]:
s3 = s1 + s2
print(s3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 1 ----> 1 s3 = s1 + s2 2 print(s3) TypeError: unsupported operand type(s) for +: 'set' and 'set'
In [4]:
s3 = s1 * s2
print(s3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 1 ----> 1 s3 = s1 * s2 2 print(s3) TypeError: unsupported operand type(s) for *: 'set' and 'set'
In [8]:
# 1. union() :-
# x.union(y) ===> It returns all elements present in both x and y
# x | y
In [15]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.union(y))
print(x | y)
print(y.union(x))
print(y | x)
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
In [16]:
# 2. intersection() :-
# common elements
# x.intersection(y)
# x & y
In [17]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.intersection(y))
print(x & y)
print(y.intersection(x))
print(y & x)
{40, 30}
{40, 30}
{40, 30}
{40, 30}
In [18]:
# 3. difference() :-
# x.difference(y)
# x - y
# The elements present in x but not in y
In [21]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.difference(y))
print(x - y)
print(y.difference(x))
print(y - x)
{10, 20}
{10, 20}
{50, 60}
{50, 60}
In [24]:
# 3. symmetric_difference() :-
# x.symmetric_difference(y)
# x ^ y
# The elements present in either x or y butu not in both
In [23]:
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print(x.symmetric_difference(y))
print(x ^ y)
print(y.symmetric_difference(x))
print(y ^ x)
{10, 50, 20, 60}
{10, 50, 20, 60}
{10, 50, 20, 60}
{10, 50, 20, 60}
# Membership Operator :-¶
In [26]:
# in, not in
In [28]:
x = {10, 20, 30, 40}
print(x)
{40, 10, 20, 30}
In [29]:
print(10 in x)
True
In [30]:
print(50 in x)
False
In [31]:
print(50 not in x)
True
# Comprehension :-¶
In [3]:
# list ---> applicable
# tuple ---> not applicable
# set ---> applicable
In [4]:
s = {x * x for x in range(1, 6)}
print(type(s))
print(s)
<class 'set'>
{1, 4, 9, 16, 25}
In [5]:
s = {2**x for x in range(1, 6)}
print(type(s))
print(s)
<class 'set'>
{32, 2, 4, 8, 16}
In [1]:
s1 = {10, 20, 30}
s2 = {20, 30, 10}
print(s1 is s2)
print(s1 == s2)
False True
In [7]:
s1 = {10, 20, 30}
s2 = {10, 20, 30}
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873356064 2947873352704
In [13]:
s1 = {10, 20, 30}
s2 = s1
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
True True 2947873356064 2947873356064
In [9]:
s1 = {10, 20, 30}
s2 = s1.copy()
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873357408 2947873352704
In [10]:
s1 = [10, 20, 30]
s2 = [10, 20, 30]
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873771776 2947873774592
In [12]:
s1 = (10, 20, 30)
s2 = (10, 20, 30)
print(s1 is s2)
print(s1 == s2)
print(id(s1))
print(id(s2))
False True 2947873830336 2947873799232
In [14]:
# For set order is not important
# indexing and slicing concepts are not applicable
In [15]:
s = {10, 20, 30}
print(s)
{10, 20, 30}
In [16]:
s[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[16], line 1 ----> 1 s[0] TypeError: 'set' object is not subscriptable
In [17]:
s = [10, 20, 30]
print(id(s))
s = [20, 30, 10]
print(id(s))
2947873665088 2947879642112
In [19]:
# WAP to delete duplicates present in the list?
In [22]:
l = eval(input("Enter a list of values:"))
print(l)
s = set(l)
print(s)
[4646, 64, 546, 46, 464, 46]
{64, 546, 4646, 46, 464}
In [23]:
l = eval(input("Enter a list of values:"))
print(l)
l1 = []
for x in l:
if x not in l1:
l1.append(x)
print(l1)
[46, 22, 21, 12, 12, 45, 45, 65, 65, 85, 95, 85, 95] [46, 22, 21, 12, 45, 65, 85, 95]
In [ ]:
# # Dictionary Data Structure :-¶
In [3]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [7]:
# keys ---> 100, 200, 300
# values ---> 'durga', 'ravi', 'shiva'
# duplicate keys are not allowed, but values can be duplicated.
# If we are trying to add key-value pair but key already present, then old value will be replaced with new value.
# order is not applicable and all elements will be inserted based on hash of keys.
# indexing and slicing concepts are not applicable.
# for keys and values we can take heterogeneous objects.
# dict is mutable.
# dict is growable.
In [6]:
d = {100: "durga", "ravi": 200, True: "shiva"}
print(d)
{100: 'durga', 'ravi': 200, True: 'shiva'}
# How to Create Dictionary :-¶
In [16]:
# If we don't know data :-
In [17]:
d = {}
print(type(d))
# or
d = dict()
print(type(d))
<class 'dict'> <class 'dict'>
In [15]:
# d[key] = value ===>
# The provided key-valule pair will be added to the dict
# If the dspecified key is already available then old value will be replaced with new value.
# d = {key1:value1, key2:value2, key3:value3}
In [13]:
d = {}
print(d)
d[100] = "durga"
d[200] = "shiva"
d[300] = "ravi"
print(d)
{}
{100: 'durga', 200: 'shiva', 300: 'ravi'}
In [14]:
d[100] = "pavan"
print(d)
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
In [18]:
d = {1, 2, 3 : 'a', 'b', 'c'}
Cell In[18], line 1 d = {1, 2, 3 : 'a', 'b', 'c'} ^ SyntaxError: invalid syntax
# Access Data From the Dictionary :-¶
In [24]:
# By using key we can access the corresponding value.
In [20]:
d = {100: "pavan", 200: "shiva", 300: "ravi"}
print(d)
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
In [21]:
print(d[200])
shiva
In [22]:
print(d[100])
pavan
In [23]:
print(d[500])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[23], line 1 ----> 1 print(d[500]) KeyError: 500
In [26]:
# Using value can we get key?
In [28]:
d = {100: "pavan", 200: "shiva", 300: "ravi"}
print(d)
key = int(input("Enter key to find corresponding value:"))
if key in d:
print(d[key])
else:
print("Specified key not available:", key)
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
Specified key not available: 352
In [ ]:
In [1]:
d = {100: "pavan", 200: "shiva", 300: "ravi"}
print(d)
print(d[200])
{100: 'pavan', 200: 'shiva', 300: 'ravi'}
shiva
In [2]:
# Quest: WAP to enter name and marks in a dictionary and display information on the screen?
In [4]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
if option.lower() == "n":
break
elif option.lower() == 'y':
continue
else:
print('Invalid Input to Continue')
break
print(d)
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Invalid Input to Continue
{'asdadf': '54', 'amsdka': '95', 'safas': '12', 'dsafads': '56'}
In [1]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
while True:
if option.lower() == "n":
option = "n"
break
elif option.lower() == "y":
option = "y"
break
else:
option = input("Your Entered option is Invalid, Please Choose Correct option [Y|N]:")
if option == "n":
break
print(d)
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
{'ram': '95', 'han': '85', 'nksdnf': "52'", 'dsaf': '5654'}
In [2]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
while True:
if option.lower() in ["y", "n"]:
break
else:
option = input(
"Your Entered option is Invalid, Please Choose Correct option [Y|N]:"
)
if option == "n":
break
print(d)
Student record inserted Successfully
Student record inserted Successfully
{'ad': '54', 'asd': '5'}
In [8]:
d = {}
while True:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
option = input("Do you want to insert one more student marks[Y|N]:")
while True:
if option.lower() not in ["y", "n"]:
option = input(
"Your Entered option is Invalid, Please Choose Correct option [Y|N]:"
)
else:
break
if option == "n":
break
print(d)
for x in d:
print("{}\t{}".format(x, d[x]))
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
{'ram': '52', 'shyam': '95', 'barry': '96'}
ram 52
shyam 95
barry 96
In [7]:
d = {}
while len(d) < 5:
name = input("Enter Student Name:")
marks = input("Enter Student Marks:")
d[name] = marks
print("Student record inserted Successfully")
print(d)
for x in d:
print("{}\t{}".format(x, d[x]))
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
Student record inserted Successfully
{'ram': '10', 'shyam': '30', 'ravi': '65', 'harry': '94', 'barry': '82'}
ram 10
shyam 30
ravi 65
harry 94
barry 82
# Update Dictionary :-¶
In [10]:
# d = {}
# d[key] = value
# If the specified key is not already available, then key-value will be added.
# If the specified key is already available, then olde value will be replaced with new value.
In [11]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
d[400] = "pavan"
print(d)
d[200] = "harry"
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
{100: 'durga', 200: 'harry', 300: 'shiva', 400: 'pavan'}
# Delete Elements from Dictionary :-¶
In [15]:
# del d[key]
# If the specified key is available, then total entry will be deleted.
# If the specified key is not available, then we will get KeyError.
In [13]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [14]:
del d[100]
print(d)
{200: 'ravi', 300: 'shiva'}
In [16]:
del d[400]
print(d)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[16], line 1 ----> 1 del d[400] 2 print(d) KeyError: 400
In [17]:
if 400 in d:
del d[400]
print(d)
{200: 'ravi', 300: 'shiva'}
In [19]:
# To remove all the entries :-
# d.clear()
# del d
In [20]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [21]:
d.clear()
print(d)
{}
In [24]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [25]:
del d
print(d)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[25], line 2 1 del d ----> 2 print(d) NameError: name 'd' is not defined
# Important Methods and Functions related to Dictionary :-¶
In [27]:
# 1. dict() :-
In [29]:
d = dict()
print(d)
print(type(d))
{}
<class 'dict'>
In [30]:
d = dict({100: "ram", 200: "durga"})
print(d)
print(type(d))
{100: 'ram', 200: 'durga'}
<class 'dict'>
In [31]:
# [(100, 'durga'), (200, 'shiva'), (300, 'ravi')] ---> List of Tuples
In [32]:
d = dict([(100, "durga"), (200, "shiva"), (300, "ravi")])
print(d)
print(type(d))
{100: 'durga', 200: 'shiva', 300: 'ravi'}
<class 'dict'>
In [33]:
d = dict(((100, "durga"), (200, "shiva"), (300, "ravi")))
print(d)
print(type(d))
{100: 'durga', 200: 'shiva', 300: 'ravi'}
<class 'dict'>
In [34]:
d = dict([[100, "durga"], [200, "shiva"], [300, "ravi"]])
print(d)
print(type(d))
{100: 'durga', 200: 'shiva', 300: 'ravi'}
<class 'dict'>
In [35]:
d = dict({[100, "durga"], [200, "shiva"], [300, "ravi"]})
print(d)
print(type(d))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[35], line 1 ----> 1 d = dict({[100, "durga"], [200, "shiva"], [300, "ravi"]}) 2 print(d) 3 print(type(d)) TypeError: unhashable type: 'list'
In [36]:
d = dict({(100, "durga"), (200, "shiva"), (300, "ravi")})
print(d)
print(type(d))
{300: 'ravi', 100: 'durga', 200: 'shiva'}
<class 'dict'>
In [39]:
# 2. len() :-
# returns the number of items in the dictionary
# item ---> key-value pair
In [40]:
d = dict({(100, "durga"), (200, "shiva"), (300, "ravi")})
print(d)
print(len(d))
{300: 'ravi', 100: 'durga', 200: 'shiva'}
3
In [47]:
# 3. get(key) :-
# returns the corresponding value.
# If specified key not available then None
# d[key] ---> KeyError
# d.get(key) ---> None
# d.get(key, default_value)
In [50]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [44]:
print(d.get(100))
durga
In [45]:
print(d.get(200))
ravi
In [46]:
print(d.get(900))
None
In [48]:
print(d.get(900, 'no value'))
no value
In [ ]:
In [2]:
# 5. pop() :-
# d.pop(key)
# remove item(key-value pair) associated with the specified key and returns the corresponding value.
# If the specified key not already available then we will get KeyError.
In [4]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [5]:
print(d.pop())
print(d)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[5], line 1 ----> 1 print(d.pop()) 2 print(d) TypeError: pop expected at least 1 argument, got 0
In [6]:
print(d.pop(200))
print(d)
ravi
{100: 'durga', 300: 'shiva'}
In [7]:
print(d.pop(500))
print(d)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[7], line 1 ----> 1 print(d.pop(500)) 2 print(d) KeyError: 500
In [14]:
# 6. popitem() :-
# d.popitem()
# It will remove an arbitrary item from the dict and returns it.
# If the dict is empty then we get KeyError
In [9]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [10]:
print(d.popitem())
print(d)
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
In [11]:
print(d.popitem())
print(d)
(200, 'ravi')
{100: 'durga'}
In [12]:
print(d.popitem())
print(d)
(100, 'durga')
{}
In [13]:
print(d.popitem())
print(d)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[13], line 1 ----> 1 print(d.popitem()) 2 print(d) KeyError: 'popitem(): dictionary is empty'
In [22]:
# 7. keys() :-
# d.keys()
In [23]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
print(d)
{'A': 100, 'B': 110, 'C': 120, 'D': 130, 'E': 140, 'F': 150, 'G': 160, 'H': 170, 'I': 180, 'J': 190, 'K': 200, 'L': 210, 'M': 220, 'N': 230, 'O': 240, 'P': 250, 'Q': 260, 'R': 270, 'S': 280, 'T': 290, 'U': 300, 'V': 310, 'W': 320, 'X': 330, 'Y': 340, 'Z': 350}
In [24]:
while len(d) != 0:
print('Processing item:', d.popitem())
Processing item: ('Z', 350)
Processing item: ('Y', 340)
Processing item: ('X', 330)
Processing item: ('W', 320)
Processing item: ('V', 310)
Processing item: ('U', 300)
Processing item: ('T', 290)
Processing item: ('S', 280)
Processing item: ('R', 270)
Processing item: ('Q', 260)
Processing item: ('P', 250)
Processing item: ('O', 240)
Processing item: ('N', 230)
Processing item: ('M', 220)
Processing item: ('L', 210)
Processing item: ('K', 200)
Processing item: ('J', 190)
Processing item: ('I', 180)
Processing item: ('H', 170)
Processing item: ('G', 160)
Processing item: ('F', 150)
Processing item: ('E', 140)
Processing item: ('D', 130)
Processing item: ('C', 120)
Processing item: ('B', 110)
Processing item: ('A', 100)
In [25]:
print(d)
{}
In [26]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
k = d.keys()
print(type(k))
print(k)
for k1 in k:
print(k1)
<class 'dict_keys'> dict_keys(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
In [29]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
for k1 in d.keys():
print(k1)
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
In [30]:
# 8. values() :-
# d.values()
In [32]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
print(d.values())
dict_values([100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350])
In [33]:
i = 0
d = {}
while i < 26:
d[chr(65 + i)] = 100 + 10 * i
i = i + 1
print(d.values())
for v in d.values():
print(v)
dict_values([100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350]) 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300 310 320 330 340 350
In [34]:
d = {100: "durga", 200: "durga", 300: "durga"}
for v in d.values():
print(v)
durga durga durga
In [36]:
# 9. items() :-
# d.items()
# item ---> key-value pair
In [39]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
i = d.items()
print(type(i))
print(i)
<class 'dict_items'> dict_items([(100, 'durga'), (200, 'ravi'), (300, 'shiva')])
In [40]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
for x in d.items():
print(x)
(100, 'durga') (200, 'ravi') (300, 'shiva')
In [43]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
for k in d.keys():
print("Key:", k)
for v in d.values():
print("Value:", v)
for k, v in d.items():
print("{}:{}".format(k, v))
Key: 100 Key: 200 Key: 300 Value: durga Value: ravi Value: shiva 100:durga 200:ravi 300:shiva
In [44]:
# 10. setdefault() :-
# d.setdefault(k, v)
# If the specified key available, then it returnsthe corresponding value.
# If the specified key not available, then the provided key-value pair will be added as a new item to the dictionary.
In [48]:
d = {100: "durga", 200: "ravi", 300: "shiva"}
print(d)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
In [53]:
print(d.setdefault(100, "sunny"))
d.setdefault(100, "sunny")
print(d)
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 500: 'bunny'}
In [54]:
print(d.setdefault(500, "bunny"))
d.setdefault(500, "bunny")
print(d)
bunny
{100: 'durga', 200: 'ravi', 300: 'shiva', 500: 'bunny'}
In [66]:
# 11. update() :-
In [55]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = {400: "sunny", 500: "bunny", 600: "harry"}
print(d1)
print(d2)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{400: 'sunny', 500: 'bunny', 600: 'harry'}
In [56]:
d1.update(d2)
print(d1)
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'sunny', 500: 'bunny', 600: 'harry'}
In [57]:
print(d2)
{400: 'sunny', 500: 'bunny', 600: 'harry'}
In [58]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = {400: "sunny", 500: "bunny", 100: "harry"}
print(d1)
print(d2)
d1.update(d2)
print(d1)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{400: 'sunny', 500: 'bunny', 100: 'harry'}
{100: 'harry', 200: 'ravi', 300: 'shiva', 400: 'sunny', 500: 'bunny'}
In [60]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = {400: "sunny", 500: "bunny", 100: "harry"}
print(d1)
print(d2)
d1.update(d2)
d2.update(d1)
print(d1)
print(d2)
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{400: 'sunny', 500: 'bunny', 100: 'harry'}
{100: 'harry', 200: 'ravi', 300: 'shiva', 400: 'sunny', 500: 'bunny'}
{400: 'sunny', 500: 'bunny', 100: 'harry', 200: 'ravi', 300: 'shiva'}
In [61]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1.copy()
print(id(d1))
print(id(d2))
1543898304192 1543899138368
In [62]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1
print(id(d1))
print(id(d2))
1543892330624 1543892330624
In [63]:
# d2 = d1 ===> duplicate reference variable and aliasing
# d2 = d1.copy() ===> duplicate object and cloning
In [64]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1.copy()
print(id(d1))
print(id(d2))
print(d1 is d2)
1543898481920 1543892379136 False
In [65]:
d1 = {100: "durga", 200: "ravi", 300: "shiva"}
d2 = d1
print(id(d1))
print(id(d2))
print(d1 is d2)
1543898489856 1543898489856 True
In [67]:
# 1. dict()
# 2. len()
# 3. clear()
# 4. get()
# d.get(key)
# d.get(key, default_value)
# 5. pop()
# 6. popitem()
# 7. keys()
# 8. values()
# 9. items()
# 10. setdefault()
# 11. update()
# 12. copy()
# d[key] = value
# del d[key]
In [69]:
# Ques: WAP to take dictionary from the keyboard and print the sum of values?
In [72]:
d = eval(input("Enter Dictionary:"))
print(d)
sum(d.values())
print("The Sum:", sum(d.values()))
{'a': 10, 'b': 20, 'v': 50}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[72], line 3 1 d = eval(input("Enter Dictionary:")) 2 print(d) ----> 3 sum(d.values()) 5 print("The Sum:", sum(d.values())) TypeError: 'int' object is not callable
In [71]:
d = eval(input("Enter Dictionary:"))
print(d)
sum = 0
for v in d.values():
sum = sum + v
print("The Sum:", sum)
The Sum: 60
In [73]:
# Ques: WAP to find the number of occurreneces of each letter present in the given string?
In [78]:
s = input("Enter any word:")
print(s)
d = {}
for ch in s:
if ch in d:
d[ch] = d[ch] + 1
else:
d[ch] = 1
print(d)
mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
In [80]:
s = input("Enter any word:")
print(s)
d = {}
for ch in s:
d[ch] = d.get(ch, 0) + 1
print(d)
for k, v in d.items():
print("{} occurs {} times".format(k, v))
mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
m occurs 1 times
i occurs 4 times
s occurs 4 times
p occurs 2 times
In [81]:
s = input("Enter any word:")
print(s)
d = {}
for ch in s:
d[ch] = d.get(ch, 0) + 1
print(d)
for k, v in sorted(d.items()):
print("{} occurs {} times".format(k, v))
mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
i occurs 4 times
m occurs 1 times
p occurs 2 times
s occurs 4 times
In [82]:
s = input("Enter any word:")
print(s)
vowels = {'a','e','i','o','u'}
d = {}
for ch in s:
if ch in vowels:
d[ch] = d.get(ch, 0) + 1
print(d)
for k, v in sorted(d.items()):
print("{} occurs {} times".format(k, v))
missipkdanskbfked vm,asd kjcvvhadsukc shad cadsjvgcjakevld jds
{'i': 2, 'a': 6, 'e': 2, 'u': 1}
a occurs 6 times
e occurs 2 times
i occurs 2 times
u occurs 1 times
In [ ]:
# # Merging of Collections :-¶
In [2]:
l1 = [10, 20, 30]
l2 = [40, 50, 60]
l3 = l1 + l2
print(l3)
[10, 20, 30, 40, 50, 60]
In [4]:
t1 = (10, 20, 30)
t2 = (40, 50, 60)
t3 = t1 + t2
print(t3)
(10, 20, 30, 40, 50, 60)
In [6]:
# List and Tuple ---> Apply
# Set and Dictionary ---> Not Apply
In [7]:
l1 = [10, 20, 30]
l2 = [40, 50, 60]
l3 = [*l1, *l2]
print(l3)
[10, 20, 30, 40, 50, 60]
In [8]:
l1 = (10, 20, 30)
l2 = (40, 50, 60)
l3 = (*l1, *l2)
print(l3)
(10, 20, 30, 40, 50, 60)
In [9]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s3 = s1 + s2
print(s3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 4 1 s1 = {10, 20, 30} 2 s2 = {40, 50, 60} ----> 4 s3 = s1 + s2 5 print(s3) TypeError: unsupported operand type(s) for +: 'set' and 'set'
In [10]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s3 = {*s1, *s2}
print(s3)
{50, 20, 40, 10, 60, 30}
In [11]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s = {"A", "B", "C"}
s3 = {*s1, *s2, *s}
print(s3)
{40, 10, 50, 'C', 20, 'A', 'B', 60, 30}
In [12]:
s1 = {10, 20, 30}
s2 = {40, 50, 60}
s = {"A", "B", "C"}
l = [*s1, *s2, *s]
print(l)
[10, 20, 30, 40, 50, 60, 'C', 'B', 'A']
In [13]:
s1 = {10, 20, 30}
s2 = (40, 50, 60)
s = ["A", "B", "C"]
list = [*s1, *s2, *s]
print(list)
[10, 20, 30, 40, 50, 60, 'A', 'B', 'C']
In [14]:
s1 = {10, 20, 30}
s2 = (40, 50, 60)
s = ["A", "B", "C"]
tuple = (*s1, *s2, *s)
print(tuple)
(10, 20, 30, 40, 50, 60, 'A', 'B', 'C')
In [16]:
s1 = {10, 20, 30}
s2 = (40, 50, 60)
s = ["A", "B", "C"]
set = {*s1, *s2, *s}
print(set)
{40, 10, 50, 'C', 20, 'A', 'B', 60, 30}
In [17]:
d1 = {100: "A", 200: "B"}
d2 = {300: "C", 400: "D"}
d3 = {500: "E", 600: "F"}
result = {}
print(result)
{}
In [18]:
result = {**d1, **d2, **d3}
print(result)
{100: 'A', 200: 'B', 300: 'C', 400: 'D', 500: 'E', 600: 'F'}
In [19]:
result = {*d1, *d2, *d3}
print(result)
{400, 100, 500, 200, 600, 300}
In [20]:
result = {*d1.values(), *d2.values(), *d3.values()}
print(result)
{'C', 'D', 'F', 'E', 'B', 'A'}
In [22]:
# # Limitations for + Operator :-
# 1. Applicable only for list, tuple but not for set and dict
# 2. Compulsory both arguments should be same type.
# # Nested Collections :-¶
In [24]:
# Collection inside Collection
# Django, DRF
# inside list, we can take tuple
# inside dict, we can take another dict
In [25]:
l = [(10, 20, 30), (40, 50, 60)]
print(l)
[(10, 20, 30), (40, 50, 60)]
In [26]:
print(l[0][1])
20
In [27]:
print(l[1][2])
60
In [28]:
d = {
"cars": ("Innova", "Honda", "BMW"),
"mobiles": ("Samsung", "Nokia", "Iphone"),
}
In [33]:
print(d["cars"])
('Innova', 'Honda', 'BMW')
In [32]:
print(d["cars"][1])
Honda
In [31]:
print(d.get("cars")[1])
Honda
In [35]:
# To display all mobile names
for mobile in d['mobiles']:
print(mobile)
Samsung Nokia Iphone
In [37]:
# # Two Restrictions :-
# Every element isnide set should be hashable.
# Hence we cannot list object as element in set.
# Every key inside dictionary should be hashable.
# For the key we cannot take list object.
In [ ]:
In [1]:
# Ques: Write a program to accept student name and marks from the keyboard and with that data creates a dictionary. Also display student marks by taking student name as input?
In [2]:
n = int(input("Enter Number of Students:"))
d = {}
while len(d) <= n:
name = input("Enter Student Name:")
marks = int(input("Enter Student Marks:"))
d[name] = marks
print("All Students Data Inserted")
print(d)
while True:
name = input("Enter Student Name to get Marks:")
if name in d:
print("The Marks of {}:{}".format(name, d.get(name)))
else:
print("Student Not Found")
option = input("Do you want to find another Student Marks [Yes|No]:")
while option.lower() not in ["yes", "no"]:
option = input("Invalid Option, Please choose Valid Option [Yes|No]:")
if option.lower() == "no":
break
print('Thanks for Using Our Application')
All Students Data Inserted
{'ram': 85, 'shyam': 93, 'harry': 75, 'pavan': 72}
Student Not Found
Student Not Found
The Marks of ram:85
Thanks for Using Our Application
# Dictionary Comprehension :-¶
In [4]:
# List ---> Applicable
# Tuple ---> Not Applicable
# Set ---> Applicabel
# Dict ---> Applicable
In [6]:
l = [x * x for x in range(1, 6)]
print(l)
[1, 4, 9, 16, 25]
In [9]:
# key:value
# {1:1, 2:4, 3:9, 4:16, 5:25}
# d = {key:value for x in range(1,6)}
In [12]:
d = {x: x * x for x in range(1, 6)}
print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
In [11]:
d = {x: x * 2 for x in range(1, 6)}
print(d)
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
In [13]:
d = {x: chr(64 + x) for x in range(1, 27)}
print(d)
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z'}
In [ ]:
In [1]:
# # Implementation of Supermarket Dictionary :-
In [2]:
# supermarket has multiple stores
# Every store has a name
# Every store has multiple items
# Every item has name and quantity
In [3]:
# key-value
# for key ---> hashable
# for value ---> we can take anything
In [34]:
supermarket = {
"store1": {
"name": "DURGA GENERAL STORE",
"items": [
{"name": "soap", "quantity": 20},
{"name": "brush", "quantity": 30},
{"name": "paste", "quantity": 40},
],
},
"store2": {
"name": "SUNNY BOOK STORE",
"items": [
{"name": "Python", "quantity": 5},
{"name": "Django", "quantity": 15},
{"name": "Devops", "quantity": 25},
{"name": "Django", "quantity": 65},
],
},
}
In [35]:
print(supermarket)
{'store1': {'name': 'DURGA GENERAL STORE', 'items': [{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]}, 'store2': {'name': 'SUNNY BOOK STORE', 'items': [{'name': 'Python', 'quantity': 5}, {'name': 'Django', 'quantity': 15}, {'name': 'Devops', 'quantity': 25}, {'name': 'Django', 'quantity': 65}]}}
In [36]:
# To print name of store1
In [37]:
print(supermarket['store1'])
{'name': 'DURGA GENERAL STORE', 'items': [{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]}
In [38]:
print(supermarket['store1']['name'])
DURGA GENERAL STORE
In [39]:
print(supermarket.get('store1'))
{'name': 'DURGA GENERAL STORE', 'items': [{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]}
In [40]:
print(supermarket.get('store1').get('name'))
DURGA GENERAL STORE
In [41]:
# To print names of all items present in store1
In [42]:
print(supermarket['store1']['items'])
[{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]
In [43]:
print(supermarket.get('store1').get('items'))
[{'name': 'soap', 'quantity': 20}, {'name': 'brush', 'quantity': 30}, {'name': 'paste', 'quantity': 40}]
In [44]:
for d in supermarket['store1']['items']:
print(d['name'])
soap brush paste
In [45]:
for d in supermarket.get('store1').get('items'):
print(d.get('name'))
soap brush paste
In [46]:
for d in supermarket.get('store1').get('items'):
print(d)
{'name': 'soap', 'quantity': 20}
{'name': 'brush', 'quantity': 30}
{'name': 'paste', 'quantity': 40}
In [47]:
# How many django books are available?
In [48]:
for d in supermarket["store2"]["items"]:
if d["name"] == "Django":
print("The Number of Django Books:", d["quantity"])
The Number of Django Books: 15 The Number of Django Books: 65
In [49]:
# Ques: Which of the following allowed in Python?
In [57]:
# 1. List inside List
# 2. Tuple inside List
# 3. List inside Tuple
# 4. Tuple inside Set
# 5. List inside Set ---> Invalid
# 6. Set inside Set ---> Invalid
# 7. List as key in Dict ---> Invalid
# 8. List as Value in Dict
# 9. Tuple as key in Dict
# 10. Tuple as Value in Dict
# 11. Set as key in Dict ---> Invalid
# 12. Set as Value in Dict
In [52]:
s = {10,20,[30,40]}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[52], line 1 ----> 1 s = {10,20,[30,40]} TypeError: unhashable type: 'list'
In [53]:
s = {10,20,{30,40}}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[53], line 1 ----> 1 s = {10,20,{30,40}} TypeError: unhashable type: 'set'
In [54]:
# # Note :-
# List, Set are not hashable types.
# Every element inside set should be hashable. Hence we cannot take list, ste inside set.
# Key of Dict should be hashable.
# Hence we cannot take list, set as inside dict.
In [58]:
# List is unhashable, but how list inside list is accepted
# In List and tuple, elements will be inserted based on order and index and PVM won't required any hash. Hence elements need not be hashable.
# But in set and dict, elements will be inserted based on hash. Hence elements should be hashable.
In [60]:
d = {[10, 20]: "ram"}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[60], line 1 ----> 1 d = {[10, 20]: "ram"} TypeError: unhashable type: 'list'
In [61]:
d = {(10, 20): "ram"}
In [62]:
d = {{10, 20}: "ram"}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[62], line 1 ----> 1 d = {{10, 20}: "ram"} TypeError: unhashable type: 'set'
In [ ]:
# # Functions :-¶
In [6]:
# DRY -- Principle
# Don't Repeat Yourself
# code reusability
In [30]:
def calc(a, b):
print("Sum:", a + b)
print("Product:", a * b)
print("Difference:", a - b)
print("Dividend:", a / b)
calc(10, 20)
calc(20, 30)
Sum: 30 Product: 200 Difference: -10 Dividend: 0.5 Sum: 50 Product: 600 Difference: -10 Dividend: 0.6666666666666666
In [8]:
# # Types of Functions :-
# 1. Built in Functions
# 2. User Defined Functions
# 1. Built in Functions :-¶
In [10]:
# predefined functions
# id()
# print()
# input()
# eval()
# len()
# 2. User Defined Functions :-¶
In [13]:
# syntax for user defined function :
# def function_name(parameters):
# ''' doc string '''
# business logic
# business logic
# business logic
# business logic
# return value
# def ---> mandatory
# return ---> optional
In [14]:
# def m2(a,b):
# some Code
In [15]:
# class Test:
# def m1(self):
# some code
In [16]:
# Functions inside class ---> Methods
In [17]:
# Ques: Write a function to print hello?
In [29]:
def wish(): # Defining a function
print("hello")
wish() # Calling a function
hello
In [22]:
wish()
print("hi")
wish()
print("hi")
wish()
print("hi")
wish()
hello hi hello hi hello hi hello
# Parameters :-¶
In [24]:
# Parameters are inputs to the function.
# If a function takes parameters, at the time of calling function, values.
In [31]:
def wish(name):
print("Hello {}, Good Morning!".format(name))
wish("Harry")
Hello Harry, Good Morning!
In [32]:
name = input("Enter Name:")
wish(name)
Hello Harry, Good Morning!
In [33]:
# Ques: WAP to take number as arguments and print its square value?
In [34]:
def squareIt(number):
print("The square of {} is : {}".format(number, number**2))
squareIt(4)
squareIt(5)
squareIt(6)
squareIt(7)
The square of 4 is : 16 The square of 5 is : 25 The square of 6 is : 36 The square of 7 is : 49
In [35]:
def add(x, y):
print("The Sum of {} and {} is : {}".format(x, y, x + y))
add(10, 20)
add(20, 30)
add(30, 40)
add(40, 50)
The Sum of 10 and 20 is : 30 The Sum of 20 and 30 is : 50 The Sum of 30 and 40 is : 70 The Sum of 40 and 50 is : 90
# Return Statements :-¶
In [37]:
# Ques: WAF to accept 2 numbers as input and return sum?
In [39]:
def add(x, y):
return x + y
result = add(10, 20)
print("Sum:", result)
Sum: 30
In [41]:
def add(x, y):
print('Calling add function...')
return x + y
add(10, 20)
Calling add function...
Out[41]:
30
In [42]:
def validate(mobile_number):
if len(mobile_number) == 10:
return True
else:
return False
mobile_number = input("Enter Mobile Number:")
result = validate(mobile_number)
print(result)
True
In [43]:
def f1():
print('Hello')
result = f1()
print(result)
Hello None
In [45]:
# Every Function in Python in return some value.
# If you are not returning any value then by default return value is None.
In [46]:
x = 10
print(id(x))
140709881824328
In [48]:
print(print(x))
10 None
In [49]:
# Ques: WAF to check whether the given number is even or odd?
In [50]:
def even_odd(x):
if x % 2 == 0:
print("It is even number")
else:
print("It is odd number")
even_odd(15)
even_odd(10)
It is odd number It is even number
In [51]:
even_odd(int(input('Enter Some Number to Check:')))
It is even number
In [52]:
def even_odd():
x = int(input("Enter some Number:"))
if x % 2 == 0:
print("It is even number")
else:
print("It is odd number")
even_odd()
It is odd number
In [53]:
def even_odd(x):
if x % 2 == 0:
return "It is even number"
else:
return "It is odd number"
result = even_odd(15)
print(result)
It is odd number
In [54]:
def show(sequence):
for x in sequence:
print(x)
show("durga")
show(range(1, 6))
d u r g a 1 2 3 4 5
In [55]:
# Ques: WAF to find Factorial of given number?
In [62]:
def factorial(x):
result = 1
while x >= 1:
result = result * x
x = x - 1
return result
for i in range(0, 11):
print("The Factorial of {} is : {}".format(i, factorial(i)))
The Factorial of 0 is : 1 The Factorial of 1 is : 1 The Factorial of 2 is : 2 The Factorial of 3 is : 6 The Factorial of 4 is : 24 The Factorial of 5 is : 120 The Factorial of 6 is : 720 The Factorial of 7 is : 5040 The Factorial of 8 is : 40320 The Factorial of 9 is : 362880 The Factorial of 10 is : 3628800
In [66]:
def factorial(x):
result = 1
while x >= 1:
result = result * x
x = x - 1
print("The Factorial of {} is : {}".format(x, result))
for i in range(0, 11):
factorial(i)
The Factorial of 0 is : 1 The Factorial of 0 is : 1 The Factorial of 0 is : 2 The Factorial of 0 is : 6 The Factorial of 0 is : 24 The Factorial of 0 is : 120 The Factorial of 0 is : 720 The Factorial of 0 is : 5040 The Factorial of 0 is : 40320 The Factorial of 0 is : 362880 The Factorial of 0 is : 3628800
In [69]:
def calc(a, b):
sum = a + b
sub = a - b
return sum, sub
x, y = calc(20, 10)
print(x, y)
print("Sum:", x)
print("Difference:", y)
30 10 Sum: 30 Difference: 10
In [70]:
x = calc(20, 10)
print(x)
(30, 10)
In [72]:
def calc(a, b):
sum = a + b
sub = a - b
return [sum, sub]
x, y = calc(20, 10)
print(x, y)
print("Sum:", x)
print("Difference:", y)
x = calc(20, 10)
print(x)
30 10 Sum: 30 Difference: 10 [30, 10]
In [ ]:
# Types of Arguments/Parameters :-¶
In [2]:
def f1(a, b): # Formal Parameters
pass
f1(10, 20) # Arguments
In [3]:
# 4 Types of Parameters/Arguments :-
# 1. Positional Arguments
# 2. Keyword Arguments
# 3. Default Arguments
# 4. Varable Length Arguments
# 1. Positional Arguments :-¶
In [6]:
def sub(a, b):
print(a - b)
In [7]:
sub(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[7], line 1 ----> 1 sub(10) TypeError: sub() missing 1 required positional argument: 'b'
In [11]:
sub(10, 20)
sub(20, 10)
# The number of arguments must be matched
# The order of arguments is important, The result may be changed if we change order
-10 10
In [12]:
sub(10, 20, 30)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[12], line 1 ----> 1 sub(10, 20, 30) TypeError: sub() takes 2 positional arguments but 3 were given
# 2. Keyword Arguments :-¶
In [38]:
# We have to pass argument values by keyword i.e by paramter name.
# The number of arguments must be matched.
# The order is not important.
In [29]:
def sub(a, b):
print(a - b)
sub(a=10, b=20)
-10
In [17]:
sub(a=10, b=20)
sub(b=20, a=10)
-10 -10
In [49]:
# # Note :-
# We can use both positional arguments and keyword arguments simultaneously, but first positional arguments then keyword arguments.
# But keyword arguments won't follow positional arguments.
# Key name should be case sensitive.
In [27]:
def sub(a, b):
print(a - b)
In [30]:
sub(a=10, b=20)
-10
In [28]:
sub(x=10, b=20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[28], line 1 ----> 1 sub(x=10, b=20) TypeError: sub() got an unexpected keyword argument 'x'
In [31]:
sub(10, b=20)
-10
In [32]:
sub(10, a=20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[32], line 1 ----> 1 sub(10, a=20) TypeError: sub() got multiple values for argument 'a'
In [33]:
sub(a=10, 20)
Cell In[33], line 1 sub(a=10, 20) ^ SyntaxError: positional argument follows keyword argument
In [34]:
sub(b=10, 20)
Cell In[34], line 1 sub(b=10, 20) ^ SyntaxError: positional argument follows keyword argument
In [36]:
def sub(a, b, c, d, e):
print(a - b)
sub(10, 20, 30, 40, e=10)
-10
In [37]:
sub(10, 20, 30, 40, d=10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[37], line 1 ----> 1 sub(10, 20, 30, 40, d=10) TypeError: sub() got multiple values for argument 'd'
In [39]:
sub(10, 20, c=30, d=40, e=10)
-10
In [40]:
sub(10, 20, d=40, e=10, c=30)
-10
In [42]:
def wish(name, msg):
print("Hello", name, msg)
In [43]:
wish("Durga", "Good Morning")
Hello Durga Good Morning
In [44]:
wish("Durga", msg="Good Morning")
Hello Durga Good Morning
In [45]:
wish(name ="Durga", "Good Morning")
Cell In[45], line 1 wish(name ="Durga", "Good Morning") ^ SyntaxError: positional argument follows keyword argument
In [46]:
wish(name="Durga", msg="Good Morning")
Hello Durga Good Morning
# 3. Default Arguments :-¶
In [50]:
def wish(name="Guest"):
print("Hello", name, "Good Morning")
In [51]:
wish()
Hello Guest Good Morning
In [53]:
wish('Durga')
Hello Durga Good Morning
In [54]:
# Positional arguments and keywords arguments we have to take at the time of calling.
# But default arguments at the time of declaration.
In [55]:
wish(name ='Durga')
Hello Durga Good Morning
In [56]:
def wish(name="Guest", msg="Good Morning"):
print("Hello", name, msg)
In [57]:
wish()
Hello Guest Good Morning
In [58]:
wish(name="Durga")
Hello Durga Good Morning
In [59]:
wish("Durga", msg="Good Evening")
Hello Durga Good Evening
In [60]:
wish("Good Evening")
Hello Good Evening Good Morning
In [61]:
wish(name="Durga", msg="Good Evening")
Hello Durga Good Evening
In [62]:
wish(msg="Good Evening")
Hello Guest Good Evening
In [63]:
wish(name="Durga", "Good Evening")
Cell In[63], line 1 wish(name="Durga", "Good Evening") ^ SyntaxError: positional argument follows keyword argument
In [64]:
def wish(name="Guest", msg="Good Morning"):
pass
In [65]:
def wish(name, msg="Good Morning"):
pass
In [66]:
def wish(name="Guest", msg):
pass
Cell In[66], line 1 def wish(name="Guest", msg): ^ SyntaxError: non-default argument follows default argument
In [67]:
# Default arguments should be last arguments. i.e after default arguments we cannot take non-default arguments.
In [68]:
def wish(msg, name="Guest"):
pass
# 4. Variable Length Arguments :-¶
In [105]:
# Varaible number of arguments: at the time of declaration/definition.
In [85]:
def f(*x):
print("The Type of x:", type(x))
print("The Number of arguments passed:", len(x))
In [86]:
f()
The Type of x: <class 'tuple'> The Number of arguments passed: 0
In [87]:
f(10)
The Type of x: <class 'tuple'> The Number of arguments passed: 1
In [88]:
f(10, 20)
The Type of x: <class 'tuple'> The Number of arguments passed: 2
In [89]:
f(10, 20, 30)
The Type of x: <class 'tuple'> The Number of arguments passed: 3
In [90]:
f(10, 20, 30, 40)
The Type of x: <class 'tuple'> The Number of arguments passed: 4
In [91]:
f(10, 20, 30, 40, 50, 60, 70, 80, 90)
The Type of x: <class 'tuple'> The Number of arguments passed: 9
In [92]:
def sum(*n):
total = 0
for n1 in n:
total = total + n1
print("Sum:", total)
In [93]:
sum(10)
Sum: 10
In [94]:
sum(10, 20)
Sum: 30
In [95]:
sum(10, 20, 30, 40, 50, 60)
Sum: 210
In [96]:
sum()
Sum: 0
In [97]:
def sum(*n):
for n1 in n:
print(n1)
In [98]:
sum(10, "durga")
10 durga
In [99]:
def sum(*n):
print(n)
sum(10, "durga")
(10, 'durga')
In [109]:
# We can use normal arguments and varaible length arguments simultaneously.
# We can take variable length argument anywhere.
In [101]:
def sum(n, *s):
print(n)
print(s)
In [102]:
sum(10, 20, 30, 40, 50)
10 (20, 30, 40, 50)
In [103]:
def sum(*s, n):
print(s)
print(n)
In [104]:
sum(10, 20, 30, 40, 50)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[104], line 1 ----> 1 sum(10, 20, 30, 40, 50) TypeError: sum() missing 1 required keyword-only argument: 'n'
In [108]:
sum(10, 20, 30, 40, 50, n=10)
(10, 20, 30, 40, 50) 10
In [110]:
# After variable lengtrh argument, if we are taking normal argument, we should provide value by using keyword only.
In [111]:
sum(10, 20, 30, 40, n=10, 50)
Cell In[111], line 1 sum(10, 20, 30, 40, n=10, 50) ^ SyntaxError: positional argument follows keyword argument
In [112]:
def sum(*s, n=0):
print(s)
print(n)
In [113]:
sum(10, 20, 30, 40, 50)
(10, 20, 30, 40, 50) 0
In [114]:
sum(10, 20, 30, 40, 50, n=60)
(10, 20, 30, 40, 50) 60
In [115]:
def sum(n=0, *s):
print(s)
print(n)
In [118]:
sum(10, 20, 30, 40, 50, n=60)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[118], line 1 ----> 1 sum(10, 20, 30, 40, 50, n=60) TypeError: sum() got multiple values for argument 'n'
In [119]:
sum(n=60, 10, 20, 30, 40, 50)
Cell In[119], line 1 sum(n=60, 10, 20, 30, 40, 50) ^ SyntaxError: positional argument follows keyword argument
In [120]:
sum(10, 20, 30, 40, 50)
(20, 30, 40, 50) 10
In [121]:
# After default arguments, we cannot take noraml arguments but we can take variable length arguments.
In [122]:
def sum(*m, *n):
print(m)
print(n)
Cell In[122], line 1 def sum(*m, *n): ^ SyntaxError: * argument may appear only once
In [123]:
# We cannot take more than one variable keyword argument.
In [124]:
def sum(*a, b, c, d, e):
pass
In [125]:
sum(1, 2, 3, 4, 5)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[125], line 1 ----> 1 sum(1, 2, 3, 4, 5) TypeError: sum() missing 4 required keyword-only arguments: 'b', 'c', 'd', and 'e'
In [ ]:
In [1]:
# 1. Positional Arguments
# 2. Keyword Arguments
# 3. Default Arguments
# 4. Variable Length Argumnets
In [3]:
# 1. Positional Arguments :-
# At the time of calling
# Order and Number are Important
In [4]:
def f1(a, b):
print(a - b)
f1(10, 20)
-10
In [7]:
# 2. Keyword Arguments :-
# At the time of calling
# Order/Position is not Important
In [6]:
def f1(a, b):
print(a - b)
f1(a=10, b=20)
-10
In [8]:
# We can use positional and keyword argumnets together but :
# First we should use positional argumnets and then keyword arguments.
In [9]:
# 3. Default Arguments :-
# At the time of declaration/creation.
# After taking default arguments, we cannot take normal arguments. But we can take variable length arguments.
In [11]:
def f1(a, b=0):
print(a - b)
f1(a=10)
f1(a=10, b=20)
10 -10
In [12]:
def f1(a=0, b):
print(a - b)
f1(a=10)
f1(a=10, b=20)
Cell In[12], line 1 def f1(a=0, b): ^ SyntaxError: non-default argument follows default argument
In [13]:
def f1(a=0, *b):
print(a - b)
f1(a=10)
f1(a=10, b=20)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[13], line 5 1 def f1(a=0, *b): 2 print(a - b) ----> 5 f1(a=10) 6 f1(a=10, b=20) Cell In[13], line 2, in f1(a, *b) 1 def f1(a=0, *b): ----> 2 print(a - b) TypeError: unsupported operand type(s) for -: 'int' and 'tuple'
In [16]:
# 4. Variable Length Arguments :-
# At the time of declaration/creation
# We can take variable length arguments anywhere.
# But after variable length argument, if we are taking any normal argument, compulsory we should pass value by keyword.
# We can take only one variable-length argument.
In [15]:
def f1(*x):
print(x)
f1(10, 20, 30, 40)
(10, 20, 30, 40)
In [18]:
def f1(*x, y):
print(x)
print(y)
In [19]:
f1(10, 20, 30, 40)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[19], line 1 ----> 1 f1(10, 20, 30, 40) TypeError: f1() missing 1 required keyword-only argument: 'y'
In [20]:
f1(10, 20, 30, y=40)
(10, 20, 30) 40
In [21]:
def fn(*var1, var2):
print(var1)
print(var2)
fn(10, "durga", 10.5, True, var2=40)
(10, 'durga', 10.5, True) 40
In [22]:
# *x ---> We can provide any number of values for x and x will become tuple.
# *args
# **x ---> We can pass any number of key-value pairs and x will become dict.
# **kwargs
In [24]:
def display(**kwargs):
print(type(kwargs))
print(kwargs)
In [25]:
display(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[25], line 1 ----> 1 display(10) TypeError: display() takes 0 positional arguments but 1 was given
In [27]:
display(name="Durga", rollno=101, narks=90)
<class 'dict'>
{'name': 'Durga', 'rollno': 101, 'narks': 90}
In [28]:
def display(**kwargs):
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(name="Durga", rollno=101, narks=90)
name=Durga rollno=101 narks=90
In [30]:
# .items ---> provide list of items
In [31]:
def display(**kwargs):
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(name="Durga", rollno=101, narks=90)
dict_items([('name', 'Durga'), ('rollno', 101), ('narks', 90)])
name=Durga
rollno=101
narks=90
In [33]:
def display(*args, **kwargs):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90)
(10, 20, 30)
dict_items([('name', 'Durga'), ('rollno', 101), ('narks', 90)])
name=Durga
rollno=101
narks=90
In [35]:
def display(*args, **kwargs, x):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90)
Cell In[35], line 1 def display(*args, **kwargs, x): ^ SyntaxError: arguments cannot follow var-keyword argument
In [37]:
def display(*args, **kwargs, x=10):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90)
Cell In[37], line 1 def display(*args, **kwargs, x=10): ^ SyntaxError: arguments cannot follow var-keyword argument
In [42]:
# After varible length argument after **kwargs, it won't except any other type of argument.
In [43]:
def display(*args, **kwargs, x=10):
print(args)
print(kwargs.items())
for k, v in kwargs.items():
print("{}={}".format(k, v))
display(10, 20, 30, name="Durga", rollno=101, narks=90, x=10)
Cell In[43], line 1 def display(*args, **kwargs, x=10): ^ SyntaxError: arguments cannot follow var-keyword argument
# Rules to Remember :-¶
In [44]:
# 1. After keyword arguments, we cannot take positional arguments.
# 2. After default arguments, we cannit take normal arguments, but we can take variable length arguments.
# 3. After Variable length arguments, if we are taking any normal argument, compulsory we should provide values by keyword only.
# 4. We can take atmost one varaible length argument.
# 5. **kwargs should be last arguments.
In [45]:
def f1(arg1, arg2, arg3=4, arg4=8):
print(arg1, arg2, arg3, arg4)
In [46]:
f1(3, 2)
3 2 4 8
In [47]:
f1(10, 20, 30, 40)
10 20 30 40
In [48]:
f1(25, 50, arg4=100)
25 50 4 100
In [49]:
f1(arg4=2, arg1=3, arg2=4)
3 4 4 2
In [50]:
f1()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[50], line 1 ----> 1 f1() TypeError: f1() missing 2 required positional arguments: 'arg1' and 'arg2'
In [52]:
f1(arg3=10, arg4=20, 30, 40)
Cell In[52], line 1 f1(arg3=10, arg4=20, 30, 40) ^ SyntaxError: positional argument follows keyword argument
In [53]:
f1(4, 5, arg2=6)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[53], line 1 ----> 1 f1(4, 5, arg2=6) TypeError: f1() got multiple values for argument 'arg2'
In [54]:
f1(4, 5, arg3=5, arg5=6)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[54], line 1 ----> 1 f1(4, 5, arg3=5, arg5=6) TypeError: f1() got an unexpected keyword argument 'arg5'
In [55]:
def f1(*x, y=20):
print(x)
print(y)
In [56]:
f1(10, 20, 30, 777)
(10, 20, 30, 40) 20
In [57]:
f1(10, 20, 30, y=777)
(10, 20, 30) 777
In [ ]:
# # Types of Variables/Variable Scopes :-¶
In [2]:
# 1. Global Variables
# 2. Local Variables
# 1. Global Variables :-¶
In [5]:
# The variables which are declared outside of the function
# Avaialable for all functions.
In [6]:
a = 10
def f1():
print(a)
def f2():
print(a)
f1()
f2()
10 10
# 2. Local Variables :-¶
In [8]:
# The variables which are declared inside of the function
# Avaialable only for that function.
In [11]:
def f1():
b = 10
print(b)
f1()
10
In [12]:
def f1():
b = 10
print(b)
def f2():
print(b)
f1()
f2()
10
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[12], line 11 7 print(b) 10 f1() ---> 11 f2() Cell In[12], line 7, in f2() 6 def f2(): ----> 7 print(b) NameError: name 'b' is not defined
In [13]:
# Gloabl ===> Global to all functions.
# Local ===> Local to a particular function.
In [1]:
a = 10 # Global variable
def f1():
a = 777 # Local variable
print(a)
def f2():
print(a)
f1()
f2()
777 10
# Global Keyword :-¶
In [9]:
# 1. To make global varaibles available to the functions so that we can perform required modifications.
In [18]:
a = 10 # Global variable
def f1():
global a # Make Global variable available to f1
a = 777
print(a)
def f2():
print(a)
f1()
f2()
777 777
In [19]:
a = 10 # Global variable
def f1():
global a = 777 # Make Global variable available to f1
print(a)
def f2():
print(a)
f1()
f2()
Cell In[19], line 5 global a = 777 # Make Global variable available to f1 ^ SyntaxError: invalid syntax
In [11]:
# 2. To declare global variables inside functions.
In [14]:
def f1():
global c # Now onwards c is global varibale but not local variable
c = 10
print(c)
def f2():
print(c)
f1()
f2()
10 10
In [16]:
def f1():
global d # Now onwards d is global varibale but not local variable
d = 10
print(d)
def f2():
print(d)
f2()
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[16], line 11 7 def f2(): 8 print(d) ---> 11 f2() Cell In[16], line 8, in f2() 7 def f2(): ----> 8 print(d) NameError: name 'd' is not defined
In [17]:
def f1():
global e # Now onwards e is global varibale but not local variable
e = 10
print(e)
def f2():
e = 777
print(e)
f1()
f2()
print(e)
10 777 10
In [22]:
f = 10
def f1():
f = 777
print(f)
f1()
print(f)
777 10
In [24]:
# How to print global varibale value inside fuction containing local variable.
# If the local and global varibale have the same name then how to differentiate values?
In [30]:
a1 = 10
def f1():
a1 = 777
print("Local Variable Value:", a1)
# How to print global variable value of 'a1'
global a1
print("Global Variable Value:", a1)
f1()
Cell In[30], line 9 global a1 ^ SyntaxError: name 'a1' is used prior to global declaration
In [31]:
a1 = 10
def f1():
a1 = 777
print("Local Variable Value:", a1)
# How to print global variable value of 'a1'
print("Global Variable Value:", globals())
f1()
Local Variable Value: 777
Global Variable Value: {'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', 'a = 10\n\n\ndef f1():\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a\n a = 777 # Local variable\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# # Global Keyword :-', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '# 2. ', '# 2. To declare global variables inside functions.', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global d # Now onwards c is global varibale but not local variable\n d = 10\n print(d)\n\n\ndef f2():\n print(d)\n\n\nf2()', 'def f1():\n global e # Now onwards e is global varibale but not local variable\n e = 10\n print(e)\n\n\ndef f2():\n e = 777\n print(e)\n\nf1()\nf2()\nprint(e)', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '# How to print global varibale value inside fuction containing local variable', '# How to print global varibale value inside fuction containing local variable.\n\n# If the local and global varibale have the same name then how to differentiate values?', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals(a1))\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()'], '_oh': {}, '_dh': [WindowsPath('c:/Users/pulki/Python/python_fundamentals')], 'In': ['', 'a = 10\n\n\ndef f1():\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a\n a = 777 # Local variable\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# # Global Keyword :-', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '# 2. ', '# 2. To declare global variables inside functions.', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', 'def f1():\n global d # Now onwards c is global varibale but not local variable\n d = 10\n print(d)\n\n\ndef f2():\n print(d)\n\n\nf2()', 'def f1():\n global e # Now onwards e is global varibale but not local variable\n e = 10\n print(e)\n\n\ndef f2():\n e = 777\n print(e)\n\nf1()\nf2()\nprint(e)', 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '# How to print global varibale value inside fuction containing local variable', '# How to print global varibale value inside fuction containing local variable.\n\n# If the local and global varibale have the same name then how to differentiate values?', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals(a1))\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()'], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000021A49C68B50>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000021A49C75990>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000021A49C75990>, 'open': <function open at 0x0000021A47C06AC0>, '_': '', '__': '', '___': '', '__vsc_ipynb_file__': 'c:\\Users\\pulki\\Python\\python_fundamentals\\58_Types_of_Variables.ipynb', '_i': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', '_ii': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', '_iii': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', '_i1': 'a = 10\n\n\ndef f1():\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', 'a': 777, 'f1': <function f1 at 0x0000021A49D6A2A0>, 'f2': <function f2 at 0x0000021A4A29D620>, '_i2': 'a = 10 # Global variable\n\n\ndef f1():\n global a\n a = 777 # Local variable\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i3': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i4': '# # Global Keyword :-', '_i5': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i6': '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '_i7': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i8': 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i9': '# 1. To make global varaibles available to the functions so that we can perform required modifications.', '_i10': '# 2. ', '_i11': '# 2. To declare global variables inside functions.', '_i12': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', 'c': 10, '_i13': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', '_i14': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf1()\nf2()', '_i15': 'def f1():\n global c # Now onwards c is global varibale but not local variable\n c = 10\n print(c)\n\n\ndef f2():\n print(c)\n\n\nf2()', '_i16': 'def f1():\n global d # Now onwards c is global varibale but not local variable\n d = 10\n print(d)\n\n\ndef f2():\n print(d)\n\n\nf2()', '_i17': 'def f1():\n global e # Now onwards e is global varibale but not local variable\n e = 10\n print(e)\n\n\ndef f2():\n e = 777\n print(e)\n\nf1()\nf2()\nprint(e)', 'e': 10, '_i18': 'a = 10 # Global variable\n\n\ndef f1():\n global a # Make Global variable available to f1\n a = 777\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i19': 'a = 10 # Global variable\n\n\ndef f1():\n global a = 777 # Make Global variable available to f1\n print(a)\n\n\ndef f2():\n print(a)\n\n\nf1()\nf2()', '_i20': 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()', 'f': 10, '_i21': 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '_i22': 'f = 10\n\n\ndef f1():\n f = 777\n print(f)\n\n\nf1()\nprint(f)', '_i23': '# How to print global varibale value inside fuction containing local variable', '_i24': '# How to print global varibale value inside fuction containing local variable.\n\n# If the local and global varibale have the same name then how to differentiate values?', '_i25': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()\nprint(f)', 'a1': 10, '_i26': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals(a1))\n\n\nf1()\nprint(f)', '_i27': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()\nprint(f)', '_i28': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals()[\'a1\'])\n\n\nf1()\nprint(f)', '_i29': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()', '_i30': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n global a1\n print("Global Variable Value:", a1)\n\n\nf1()', '_i31': 'a1 = 10\n\n\ndef f1():\n a1 = 777\n print("Local Variable Value:", a1)\n\n # How to print global variable value of \'a1\'\n print("Global Variable Value:", globals())\n\n\nf1()'}
In [33]:
a1 = 10
def f1():
a1 = 777
print("Local Variable Value:", a1)
# How to print global variable value of 'a1'
print("Global Variable Value:", globals()['a1'])
print("Global Variable Value:", globals().get('a1'))
f1()
Local Variable Value: 777 Global Variable Value: 10 Global Variable Value: 10
In [ ]:
In [2]:
a = 10
for i in range(1):
b = 20
print(a, b)
10 20
# # Recursive Functions :-¶
In [6]:
# A function that calls itself is known as Recursive Function.
# factorial(n) = n * (n-1) * (n-2) * ....1
# factorial(n) = n * factorial(n-1)
In [7]:
# 1. We can reduce the length of the code and improves readability.
# 2. We can solve very complex problems also very easily.
In [15]:
def factorial(n):
print("Finding Factorial of", n)
if n == 0:
result = 1
else:
result = n * factorial(n - 1)
print("Completion of Finding Factorial of {} and Result is {}".format(n, result))
return result
print("Factorial :", factorial(4))
Finding Factorial of 4 Finding Factorial of 3 Finding Factorial of 2 Finding Factorial of 1 Finding Factorial of 0 Completion of Finding Factorial of 0 and Result is 1 Completion of Finding Factorial of 1 and Result is 1 Completion of Finding Factorial of 2 and Result is 2 Completion of Finding Factorial of 3 and Result is 6 Completion of Finding Factorial of 4 and Result is 24 Factorial : 24
In [23]:
def fib(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
print(fib(4))
3
In [24]:
print(fib(5))
5
In [25]:
print(fib(6))
8
In [ ]:
# # Anonymous Fuctions/ Lambda Functions :-¶
In [1]:
# Nameless functions are called anonymous functions.
In [3]:
# # Normal Function :-
# By using def keyword
# function name: squareIt
In [4]:
def squareIt(n):
return n * n
# Anonymous Function :-¶
In [6]:
# We have to use lambda keyword
# lambda n : n * n
# lambda arguments_list:expression
In [9]:
s = lambda n: n * n
print("The Square is {}".format(s(4)))
The Square is 16
In [10]:
# Lambda Function to find sum of 2 given numbers?
In [12]:
s = lambda a, b: a + b
print("Sum:", s(10, 20))
Sum: 30
In [13]:
# To find biggest of 2 numbers?
In [17]:
s = lambda a, b: a if a > b else b
print("Biggest Number is", s(10, 20))
Biggest Number is 20
In [15]:
# To find biggest of 3 numbers?
In [16]:
s = lambda a, b, c: a if a > b and a > c else b if b > c else c
print("Biggest Number is", s(10, 20, 30))
Biggest Number is 30
In [18]:
# # Python Lambda functions are always single line functions only.
In [ ]:
In [1]:
# # Lmabda Functions :-
In [3]:
# We can pass a function as argument to another functions.
# In such cases Lambda functions are best choice.
# filter()
# map()
# reduce()
# 1. filter() Function :-¶
In [10]:
# To filter values based on some condition.
In [7]:
# 10 values filter top 3 values.
# 10 numbers filter only even numbers.
# input = [1, 2, 3, 4, 5, 6, 7, 8]
# [2, 4, 6, 8]
# filter(function, sequence)
In [12]:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
l = [0, 5, 10, 15, 20, 25]
output = filter(is_even, l)
print(type(output))
print(output)
<class 'filter'> <filter object at 0x0000026C05F20DF0>
In [13]:
l = [0, 5, 10, 15, 20, 25]
output = list(filter(is_even, l))
print(type(output))
print(output)
<class 'list'> [0, 10, 20]
In [1]:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
l = [0, 5, 10, 15, 20, 25]
output = []
for x in l:
if is_even(x) == True:
output.append(x)
print(type(output))
print(output)
<class 'list'> [0, 10, 20]
In [4]:
# It means filter internally looping for each value present in list.
In [6]:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
lambda n: n % 2 == 0
Out[6]:
<function __main__.<lambda>(n)>
In [7]:
l = [0, 5, 10, 15, 20, 25]
evens = list(filter(lambda n: n % 2 == 0, l))
odds = list(filter(lambda n: n % 2 != 0, l))
print(evens)
print(odds)
[0, 10, 20] [5, 15, 25]
In [8]:
t = ("A", "AA", "AAA", "AAAA", "AAAAA")
# return all strings where length is >= 3
output = list(filter(lambda s: len(s) >= 3, t))
print(output)
['AAA', 'AAAA', 'AAAAA']
In [9]:
# List of employee objects. List out all employees which can go to pub?
# his salary is > 10000 and he has gf and his age > 21
# l = [e1, e2, e3, e4]
# output = filter(lambda e:e.sal > 10000 and e.age > 21 and e.hasgf == True, l)
# 2. map() Function :-¶
In [12]:
# filter()
# input : 10 elements
# output : 10 or less
# map()
# input : 10 elements
# output : 10 elements
# For every input value, generate output value based on some operation increment 10% salary for every employee.
In [ ]:
# map(function, sequence)
In [17]:
def squarIt(n):
return n * n
l = [1, 2, 3, 4, 5]
m = map(squarIt, l)
print(type(m))
print(m)
<class 'map'> <map object at 0x00000216D4BB6530>
In [16]:
l = [1, 2, 3, 4, 5]
m = list(map(squarIt, l))
print(type(m))
print(m)
<class 'list'> [1, 4, 9, 16, 25]
In [22]:
# # without lambda function :-
def squarIt(n):
return n * n
l = [1, 2, 3, 4, 5]
m = list(map(squarIt, l))
print(type(m))
print(m)
# # with lambda function :-
l = [1, 2, 3, 4, 5]
m = list(map(lambda n: n * n, l))
print(type(m))
print(m)
<class 'list'> [1, 4, 9, 16, 25] <class 'list'> [1, 4, 9, 16, 25]
In [21]:
l = [1, 2, 3, 4, 5]
m = list(map(lambda n: 2 * n, l))
print(m)
[2, 4, 6, 8, 10]
In [ ]:
In [1]:
l = [0, 5, 10, 15, 20, 25]
# list out all odd numberws from the list
output = list(filter(lambda n: n % 2 != 0, l))
print(output)
[5, 15, 25]
In [2]:
# list out all numbers which are divisible by 3
output = list(filter(lambda n: n % 3 == 0, l))
print(output)
[0, 15]
In [3]:
# list = [0, 5, 10, 15, 20, 25]
# # list out all odd numberws from the list
# output = list(filter(lambda n: n % 2 != 0, list))
# print(output)
# # TypeError Traceback (most recent call last)
# # Cell In[3], line 5
# # 1 list = [0, 5, 10, 15, 20, 25]
# # 3 # list out all odd numberws from the list
# # ----> 5 output = list(filter(lambda n: n % 2 != 0, list))
# # 6 print(output)
# # TypeError: 'list' object is not callable
In [5]:
list1 = [0, 5, 10, 15, 20, 25]
# list out all odd numberws from the list
output = list(filter(lambda n: n % 2 != 0, list1))
print(output)
[5, 15, 25]
In [7]:
# create a new list with double of values present in list1
output = list(map(lambda n: 2 * n, list1))
print(output)
[0, 10, 20, 30, 40, 50]
In [9]:
# create a new list with numbers which are divisible by 3
output = list(map(lambda n: n % 3 == 0, list1))
print(output)
[True, False, False, True, False, False]
In [10]:
# input : 10 values
# output :
# filter() ---> 10 or less
# map() ---> 10
In [11]:
# map(function, list)
# We can use map function on multiple list also
In [12]:
l1 = [1, 2, 3, 4]
l2 = [10, 20, 30, 40]
# Generate output by multiplying values from both lists
output = list(map(lambda x, y: x * y, l1, l2))
print(output)
[10, 40, 90, 160]
In [13]:
l1 = [1, 2, 3, 4, 5]
l2 = [10, 20, 30, 40, 50, 60, 70]
# Generate output by multiplying values from both lists
output = list(map(lambda x, y: x * y, l1, l2))
print(output)
[10, 40, 90, 160, 250]
# 3. reduce() Function :-¶
In [16]:
# reduce(function, sequence)
In [15]:
# input : 10 values
# output :
# filter() ---> 10 or less
# map() ---> 10
# reduce() ---> 1
In [18]:
l = [10, 20, 30, 40, 50]
result = reduce(lambda x, y: x + y, l)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[18], line 3 1 l = [10, 20, 30, 40, 50] ----> 3 result = reduce(lambda x,y:x+y,) NameError: name 'reduce' is not defined
In [19]:
from functools import *
In [21]:
l = [10, 20, 30, 40, 50]
result = reduce(lambda x, y: x + y, l)
print(result)
150
In [24]:
# print the sum of numbers from 1 to 100
result = reduce(lambda x, y: x + y, range(1, 101))
print(result)
5050
In [25]:
result = reduce(lambda x, y: x * y, range(1, 4))
print(result)
6
In [26]:
def multiply(x, y):
return x * y
result = reduce(multiply, range(1, 4))
print(result)
6
In [27]:
# In the above example we have not pass the parameter to multiply then how it is working?
# We are not calling multiple fucntion. reduce() function is calling internally.
In [ ]:
# # Modules :-¶
In [2]:
# A group of functions, variables and classes saved to a file, which is nothing but module.
# Every Python file (.py file) is a module.
# Advantages of Module :-
# 1. Code Reusability
# 2. Readability
# 3. Maintainability
# 4. Development Time
# 5. Cost of Project
In [7]:
x = 888
name = "DURGASOFT"
def add(a, b):
print("SUM : ", a + b)
def product(a, b):
print("PRODUCT : ", a * b)
# Save by file name durgamath.py
In [8]:
# import modulename
# modulename.varaiblename
# modulename.functionname()
In [9]:
import durgamath
print(durgamath.x)
print(durgamath.name)
888 DURGASOFT
In [11]:
durgamath.add(10, 20)
SUM : 30
In [12]:
durgamath.product(10, 20)
PRODUCT : 200
In [14]:
# .pyc file will be generated for modules in __pycache__ which we wrote when we call them or when we use.
# .pyc file will be not generated for normal .py file unless we use it as a module.
In [ ]:
# Module Name Aliasing :-¶
In [5]:
import durgamath as dm
print(dm.x)
print(dm.name)
dm.add(10, 20)
dm.product(10, 20)
888 DURGASOFT SUM : 30 PRODUCT : 200
In [6]:
# Once we define alias name, we cannot use original name.
# from import :-¶
In [11]:
# Usually we can acces members of a module by using module name.
# If we don't want to use module name then we should go for from import.
# We can access members directly.
In [12]:
from durgamath import x, name
print(x)
print(name)
888 DURGASOFT
In [13]:
add(10,20)
SUM : 30
In [16]:
from durgamath import * # to import everything from file
print(dm.x)
print(dm.name)
dm.add(10, 20)
dm.product(10, 20)
888 DURGASOFT SUM : 30 PRODUCT : 200
In [17]:
# We can write import statement anywhere in the code it is not compulsory to add import as 1st statement.
# Member Aliasing :-¶
In [20]:
from durgamath import add as a, product as b, name as n
print(n)
a(10, 20)
b(10, 20)
DURGASOFT SUM : 30 PRODUCT : 200
In [21]:
a(10, 20, 30)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[21], line 1 ----> 1 a(10, 20, 30) TypeError: add() takes 2 positional arguments but 3 were given
In [24]:
# from durgamath as dm import add as a, product as p
# is this right?
# No, it is not correct.
# Various Possibilities of import :-¶
In [26]:
# import module1
# import module1, module2, module3
# import module1 as m1
# import module1 as m1, module2 as m2, module3 as m3
# from module1 import member1
# from module1 import member1, member2, member3
# from module import *
# from module import member1 as m1
# from module import member1 as m1, member2 as m2
# from module1, module2 import * ===> Invalid
# Module Naming Conflicts :-¶
In [29]:
from module1 import *
add(10, 20)
module1 add function SUM: 30
In [30]:
from module2 import *
add(10, 20)
module2 add function SUM: 30
In [31]:
from module1 import *
from module2 import *
add(10, 20)
module2 add function SUM: 30
In [33]:
from module1 import *
from module2 import *
def add(a, b):
print("Current Module Add Function")
print("SUM:", a + b)
add(10, 20)
Current Module Add Function SUM: 30
In [34]:
from module1 import *
def add(a, b):
print("Current Module Add Function")
print("SUM:", a + b)
from module2 import *
add(10, 20)
module2 add function SUM: 30
In [37]:
# In the case of conflicts, python will always consider the most recent copy.
x = 10
print(x)
x = 20
print(x)
x = 30
print(x)
10 20 30
In [39]:
# The most recent copy ---> order wise which is avaialable at last.
In [40]:
# How to call module1 add function?
# Two Ways :-¶
In [44]:
# 1st way :-
In [41]:
import module1
import module2
module1.add(10, 20)
module2.add(10, 20)
module1 add function SUM: 30 module2 add function SUM: 30
In [46]:
# 2nd way :-
In [42]:
from module1 import add as m1
from module2 import add as m2
m1.add(10, 20)
m2.add(10, 20)
module1 add function SUM: 30 module2 add function SUM: 30
# # Reloading of Module :-¶
In [48]:
# import module will be loading only once in PVM whether you call it in multiple files multiple times.
# By default module will be loaded only once eventhough we are importing multiple times.
In [49]:
# Advantage :-
# Performance is more
# Problem :-
# We are missing updations of that module.
In [50]:
import module1
module1.add(10, 20)
module1 add function SUM: 30
In [51]:
import module1
module1.add(10, 20)
module1 add function SUM: 30
In [52]:
import time
import module1
module1.add(10, 20)
print("Progrsam Entering into Sleeping State")
time.sleep(45)
print("Just Wake up and calling Updated Fuction")
import module1
module1.product(10, 20)
module1 add function SUM: 30 Progrsam Entering into Sleeping State Just Wake up and calling Updated Fuction
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[52], line 10 7 print("Just Wake up and calling Updated Fuction") 8 import module1 ---> 10 module1.product(10, 20) AttributeError: module 'module1' has no attribute 'product'
In [ ]:
# reload()
# imp module
In [53]:
import time
import imp
import module1
module1.add(10, 20)
print("Progrsam Entering into Sleeping State")
time.sleep(45)
print("Just Wake up and calling Updated Fuction")
imp.reload(module1)
module1.product(10, 20)
C:\Users\pulki\AppData\Local\Temp\ipykernel_7632\3697301949.py:2: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import imp
module1 add function SUM: 30 Progrsam Entering into Sleeping State Just Wake up and calling Updated Fuction PRODUCT : 200
In [54]:
# My Python Program keep on printing share price values.
# Some module is available to provide shares data.
In [ ]:
# Without Reloading program if we run program second time updation is occur?
# PVM will be stopped
# PVM will be started again
# dir() and help() functions :-¶
# Finding Members of Module by using dir() function :-¶
In [2]:
# Just To list out members of a module
# dir() ---> To listout members of current module
# dir(module_name) ---> To listout members of specified module
In [3]:
a = 10
b = 20
def add(a, b):
return a + b
def product(a, b):
return a * b
# To listout all members of current module
print(dir())
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '__vsc_ipynb_file__', '_dh', '_i', '_i1', '_i2', '_i3', '_ih', '_ii', '_iii', '_oh', 'a', 'add', 'b', 'exit', 'get_ipython', 'module1', 'open', 'product', 'quit']
In [4]:
# For every module, PVM will add several predefined variables, which are internally used by PVM. Even these varaibles can be used by programmer based on his requirement.
In [5]:
# To list out all members of math module
import math
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
# Help documentation of a Module :-¶
In [6]:
# help()
In [7]:
import math
help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
cbrt(x, /)
Return the cube root of x.
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n.
Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0.
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
dist(p, q, /)
Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.
Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
exp2(x, /)
Return 2 raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(n, /)
Find n!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> value
Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y).
For example, the hypotenuse of a 3/4/5 right triangle is:
>>> hypot(3.0, 4.0)
5.0
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /)
Return the integer part of the square root of the input.
lcm(*integers)
Least Common Multiple.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
nextafter(x, y, /)
Return the next floating-point value after x towards y.
perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order.
Evaluates to n! / (n - k)! when k <= n and evaluates
to zero when k > n.
If k is not specified or is None, then k defaults to n
and the function returns n!.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
pow(x, y, /)
Return x**y (x to the power of y).
prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method.
ulp(x, /)
Return the value of the least significant bit of the float x.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
(built-in)
In [8]:
import random
help(random)
Help on module random:
NAME
random - Random variable generators.
MODULE REFERENCE
https://docs.python.org/3.11/library/random.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
distributions on the real line:
------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull
distributions on the circle (angles 0 to 2pi)
---------------------------------------------
circular uniform
von Mises
General notes on the underlying Mersenne Twister core generator:
* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.
CLASSES
_random.Random(builtins.object)
Random
SystemRandom
class Random(_random.Random)
| Random(x=None)
|
| Random number generator base class used by bound module functions.
|
| Used to instantiate instances of Random to get generators that don't
| share state.
|
| Class Random can also be subclassed if you want to use a different basic
| generator of your own devising: in that case, override the following
| methods: random(), seed(), getstate(), and setstate().
| Optionally, implement a getrandbits() method so that randrange()
| can cover arbitrarily large ranges.
|
| Method resolution order:
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu=0.0, sigma=1.0)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| getstate(self)
| Return internal state; can be passed to setstate() later.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu=0.0, sigma=1.0)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randbytes(self, n)
| Generate n random bytes.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(stop) or range(start, stop[, step]).
|
| Roughly equivalent to ``choice(range(start, stop, step))`` but
| supports arbitrarily large ranges and is optimized for common cases.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| seed(self, a=None, version=2)
| Initialize internal state from a seed.
|
| The only supported seed types are None, int, float,
| str, bytes, and bytearray.
|
| None or no argument seeds from current time or from an operating
| system specific randomness source if available.
|
| If *a* is an int, all bits are used.
|
| For version 2 (the default), all of the bits are used if *a* is a str,
| bytes, or bytearray. For version 1 (provided for reproducing random
| sequences from older versions of Python), the algorithm for str and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x)
| Shuffle list x in place, and return None.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __init_subclass__(**kwargs)
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Methods inherited from _random.Random:
|
| getrandbits(self, k, /)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| random(self, /)
| random() -> x in the interval [0, 1).
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) class method of _random.Random
| Create and return a new object. See help(type) for accurate signature.
class SystemRandom(Random)
| SystemRandom(x=None)
|
| Alternate random number generator using sources provided
| by the operating system (such as /dev/urandom on Unix or
| CryptGenRandom on Windows).
|
| Not available on all systems (see os.urandom() for details).
|
| Method resolution order:
| SystemRandom
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| randbytes(self, n)
| Generate n random bytes.
|
| random(self)
| Get the next random number in the range 0.0 <= X < 1.0.
|
| seed(self, *args, **kwds)
| Stub method. Not used for a system random number generator.
|
| setstate = _notimplemented(self, *args, **kwds)
|
| ----------------------------------------------------------------------
| Methods inherited from Random:
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu=0.0, sigma=1.0)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu=0.0, sigma=1.0)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(stop) or range(start, stop[, step]).
|
| Roughly equivalent to ``choice(range(start, stop, step))`` but
| supports arbitrarily large ranges and is optimized for common cases.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| shuffle(self, x)
| Shuffle list x in place, and return None.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods inherited from Random:
|
| __init_subclass__(**kwargs)
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Random:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) class method of _random.Random
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
betavariate(alpha, beta) method of Random instance
Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
choice(seq) method of Random instance
Choose a random element from a non-empty sequence.
choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance
Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
expovariate(lambd) method of Random instance
Exponential distribution.
lambd is 1.0 divided by the desired mean. It should be
nonzero. (The parameter would be called "lambda", but that is
a reserved word in Python.) Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.
gammavariate(alpha, beta) method of Random instance
Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
gauss(mu=0.0, sigma=1.0) method of Random instance
Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
getrandbits(k, /) method of Random instance
getrandbits(k) -> x. Generates an int with k random bits.
getstate() method of Random instance
Return internal state; can be passed to setstate() later.
lognormvariate(mu, sigma) method of Random instance
Log normal distribution.
If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.
normalvariate(mu=0.0, sigma=1.0) method of Random instance
Normal distribution.
mu is the mean, and sigma is the standard deviation.
paretovariate(alpha) method of Random instance
Pareto distribution. alpha is the shape parameter.
randbytes(n) method of Random instance
Generate n random bytes.
randint(a, b) method of Random instance
Return random integer in range [a, b], including both end points.
random() method of Random instance
random() -> x in the interval [0, 1).
randrange(start, stop=None, step=1) method of Random instance
Choose a random item from range(stop) or range(start, stop[, step]).
Roughly equivalent to ``choice(range(start, stop, step))`` but
supports arbitrarily large ranges and is optimized for common cases.
sample(population, k, *, counts=None) method of Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
Repeated elements can be specified one at a time or with the optional
counts parameter. For example:
sample(['red', 'blue'], counts=[4, 2], k=5)
is equivalent to:
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
To choose a sample from a range of integers, use range() for the
population argument. This is especially fast and space efficient
for sampling from a large population:
sample(range(10000000), 60)
seed(a=None, version=2) method of Random instance
Initialize internal state from a seed.
The only supported seed types are None, int, float,
str, bytes, and bytearray.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If *a* is an int, all bits are used.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
setstate(state) method of Random instance
Restore internal state from object returned by getstate().
shuffle(x) method of Random instance
Shuffle list x in place, and return None.
triangular(low=0.0, high=1.0, mode=None) method of Random instance
Triangular distribution.
Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution
uniform(a, b) method of Random instance
Get a random number in the range [a, b) or [a, b] depending on rounding.
vonmisesvariate(mu, kappa) method of Random instance
Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
weibullvariate(alpha, beta) method of Random instance
Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.
DATA
__all__ = ['Random', 'SystemRandom', 'betavariate', 'choice', 'choices...
FILE
c:\users\pulki\anaconda3\envs\personal\lib\random.py
In [9]:
# help() will give detailed information.
# dir() will just list members of a module.
# Extra Members added by PVM for every Module :-¶
In [10]:
# For every module, PVM will add several prdefined variabled, which are internally used by PVM. Even these variables can be used by programmer based on his requirement.
# __doc__
# __file__
# __name__
# __loader__
# __package__
In [11]:
print(dir())
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '__vsc_ipynb_file__', '_dh', '_i', '_i1', '_i10', '_i11', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'add', 'b', 'exit', 'get_ipython', 'math', 'module1', 'open', 'product', 'quit', 'random']
In [12]:
print(__loader__)
None
In [13]:
print(__builtins__)
<module 'builtins' (built-in)>
In [14]:
print(__builtin__)
<module 'builtins' (built-in)>
In [15]:
print(__doc__)
Automatically created module for IPython interactive environment
In [16]:
print(__package__)
None
In [17]:
print(__vsc_ipynb_file__)
c:\Users\pulki\Python\python_fundamentals\65_Finding_Members_of_Modules.ipynb
In [18]:
# # __doc__ :-
In [19]:
# This variable holds documentation string.
In [20]:
""" This code is written by Pulkit Chahal """
print(__doc__)
This code is written by Pulkit Chahal
In [21]:
""" This code is written by Pulkit Chahal """
""" This code is written by Chahal """
""" This code is written by Pulkit """
print(__doc__)
This code is written by Pulkit
In [22]:
import math
print(math.__doc__)
This module provides access to the mathematical functions defined by the C standard.
In [23]:
import random
print(random.__doc__)
Random variable generators.
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
distributions on the real line:
------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull
distributions on the circle (angles 0 to 2pi)
---------------------------------------------
circular uniform
von Mises
General notes on the underlying Mersenne Twister core generator:
* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.
In [24]:
# # __file__ :-
In [25]:
# To get the location of file.
In [26]:
print("File Name:", __file__)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[26], line 1 ----> 1 print("File Name:", __file__) NameError: name '__file__' is not defined
In [49]:
import os
print("Absolute Path:", os.path.abspath(__vsc_ipynb_file__))
Absolute Path: c:\Users\pulki\Python\python_fundamentals\65_Finding_Members_of_Modules.ipynb
In [27]:
print("Directory:", os.path.dirname(os.path.abspath(__vsc_ipynb_file__)))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[27], line 1 ----> 1 print("Directory:", os.path.dirname(os.path.abspath(__vsc_ipynb_file__))) NameError: name 'os' is not defined
In [28]:
# # __name__ :-
In [29]:
# py module1.py ===> Direct execution of module1.py
# py test.py ===> Indirect execution of module1.py
In [30]:
print(__name__)
__main__
In [31]:
import module1
print("test module")
test module
In [32]:
# Module1 file
print("Module1 Execution")
Module1 Execution
In [33]:
# __name__ ---> Magic Variable
# __name__
# ===> Direct Execution : __main__
# It means we are executing module1 as main program.
# ===> Indirect Execution : modulename (module1)
In [34]:
# __name__ ===> __main__ (DE)
# ===> module1 (IE)
In [35]:
if __name__ == '___main__':
print('Executing Directly')
else:
print('Executing Indiretly because of import statement')
Executing Indiretly because of import statement
In [36]:
# Module1 file
def f1():
print("f1 function")
def f2():
print("f2 function")
def f3():
print("f3 function")
def f4():
print("f4 function")
f1()
f2()
f3()
f4()
f1 function f2 function f3 function f4 function
In [37]:
import module1
print("We required only some functions but not all")
module1.f1()
We required only some functions but not all f1 function
In [ ]:
# # Working with Random Module :-¶
In [2]:
# Random module contains several functions to generate random numbers.
# Developing Games
# Cryptography
# OTP
# Random password
In [3]:
# 1. random()
# 2. uniform()
# 3. randint()
# 4. randrange()
# 5. choice()
# 1. random() :-¶
In [6]:
# generate some float values between 0 and 1 (not inclusive)
# 0.9999345
# 0.1234878
In [21]:
from random import *
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
0.6464542100401829 0.010675848165000446 0.626119271169842 0.9968781442082784 0.008614968664742984 0.589771783023502 0.409783533525354 0.8431020634036197 0.48870048075470374 0.3819780839674809 0.12230734210818128
# 2. uniform() :-¶
In [13]:
# To generate random float vlaue between 2 given numbers (not inclusive)
# uniform(1,10)
In [17]:
from random import *
for i in range(10):
print(uniform(1, 10))
3.1347665605027677 6.814167460300179 9.507224080637071 7.45048372921796 1.670982266184999 5.7269930756381235 2.172093103180653 2.317205953537269 4.6647954685826205 5.140179460010281
# 3. randint() :-¶
In [22]:
# To generate a random interger between 2 given numbers (inclusive)
# randint(1, 10) ---> 1 to 10 including 1 and 10
In [28]:
from random import *
for i in range(10):
print(randint(1, 10))
1 5 8 7 7 5 1 10 5 3
# 4. randrange([begin], end, [step]) :-¶
In [31]:
# Returns a random number from range
# begin <= x < end
# begin is optional and default value is 0.
# step is optional and default value is 1.
# randrane(10) ---> generates a random number from 0 to 9
# randrange(1, 10) ---> generates a random number from 1 to 10
# randrange(1, 11, 2) ---> generates a random number from 1 to 10 by increment of 2
# [1, 3, 5, 7, 9]
# randrange(0, 11, 2) ---> generates a random number from 0 to 10 by increment of 2
# [0, 2, 4, 6, 8]
In [32]:
from random import *
for i in range(10):
print(randrange(10))
8 1 1 5 5 9 6 7 4 6
In [33]:
from random import *
for i in range(10):
print(randrange(1, 11))
4 3 2 4 5 7 6 8 3 2
In [34]:
from random import *
for i in range(10):
print(randrange(1, 11, 2))
5 3 3 1 3 3 5 3 7 5
In [37]:
from random import *
for i in range(10):
print(randrange(0, 11, 2))
2 2 10 0 0 6 10 0 6 8
# 5. choice() :-¶
In [41]:
# It won't generate random number.
# It will generate a random object from the given sequence.
In [44]:
from random import *
l = ["Sunny", "Bunny", "Chinny", "Vinny", "Pinny"]
for i in range(10):
print(choice(l))
Vinny Chinny Pinny Bunny Chinny Pinny Sunny Pinny Pinny Sunny
In [47]:
from random import *
alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(10):
print(choice(alphabets))
S W W K Y G n y a B
In [48]:
# 1. To genrate 6-digit random number which can be used as OTP?
In [55]:
from random import *
print(
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
)
5 4 0 4 5 3
In [56]:
from random import *
print(
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
sep="",
)
092666
In [57]:
from random import *
for i in range(10):
print(
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
randint(0, 9),
sep="",
)
239368 411586 955018 891601 161595 783737 720103 579960 681697 663860
In [59]:
# 2. Random pwd of 6 length?
# where 1, 3, 5 are alphabet symbols
# 2, 4, 6 are digits
In [61]:
from random import *
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
for i in range(10):
print(
choice(alphabets)
+ choice(digits)
+ choice(alphabets)
+ choice(digits)
+ choice(alphabets)
+ choice(digits)
)
B2E3X5 H2H4F1 T1Y7F0 V0M0H4 G1G4E6 V4A5S8 P7J2S1 W0T9N3 L7B5X5 O1U3M0
In [ ]:
In [20]:
from random import *
alphabets = "abcdefghijklmnopqrstuvwxyz"
digits = "0123456789"
cities = ["Hyderabad", "Chennai", "Banglore", "Pune", "Delhi", "Mumbai"]
designations = [
"Software Engineer",
"Senior Software Engineer",
"Team Lead",
"Project Manager",
"Project Lead",
]
def get_fake_name():
name = choice(alphabets).upper()
n = randint(2, 6)
for i in range(n):
name = name + choice(alphabets)
return name
def get_fake_eno():
eno = "e-"
for i in range(4):
eno = eno + str(randint(0, 9))
return eno
def get_fake_salary():
esal = uniform(10000, 50000)
return esal
def get_fake_city():
city = choice(cities)
return city
def get_fake_mno():
mno = choice("6789")
for i in range(9):
mno = mno + choice(digits)
return mno
def get_fake_designation():
designation = choice(designations)
return designation
def get_fake_emp_data():
print("Employee Name :", get_fake_name())
print("Employee Number :", get_fake_eno())
print("Employee Salary : {:.2f}".format(get_fake_salary()))
print("Employee City :", get_fake_city())
print("Employee Mobile Number :", get_fake_mno())
print("Employee Designation :", get_fake_designation())
get_fake_emp_data()
Employee Name : Wefp Employee Number : e-0714 Employee Salary : 26959.20 Employee City : Mumbai Employee Mobile Number : 7147705020 Employee Designation : Project Lead
In [22]:
for i in range(3):
get_fake_emp_data()
Employee Name : Blysth Employee Number : e-8084 Employee Salary : 18230.72 Employee City : Banglore Employee Mobile Number : 7672497334 Employee Designation : Project Lead Employee Name : Cdxvdsr Employee Number : e-8162 Employee Salary : 10383.68 Employee City : Pune Employee Mobile Number : 8985711489 Employee Designation : Project Lead Employee Name : Axaz Employee Number : e-1870 Employee Salary : 16295.46 Employee City : Delhi Employee Mobile Number : 6993463914 Employee Designation : Team Lead
In [ ]:
# # Working with Math Module :-¶
In [2]:
# Math module defines several functions which can be used for mathematical operations.
# sqrt(x)
# ceil(x)
# floor(x)
# fabs(x)
# log(x)
# sin(x)
# tan(x)
In [4]:
from math import *
print(sqrt(4))
2.0
In [5]:
print(ceil(10.1))
11
In [6]:
print(ceil(10.5))
11
In [7]:
print(floor(10.1))
10
In [8]:
print(floor(10.4))
10
In [9]:
print(floor(10.5))
10
In [10]:
print(floor(10.6))
10
In [11]:
print(fabs(10.6))
10.6
In [12]:
print(fabs(-10.6))
10.6
In [13]:
import math
help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
cbrt(x, /)
Return the cube root of x.
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n.
Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0.
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
dist(p, q, /)
Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.
Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
exp2(x, /)
Return 2 raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(n, /)
Find n!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> value
Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y).
For example, the hypotenuse of a 3/4/5 right triangle is:
>>> hypot(3.0, 4.0)
5.0
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /)
Return the integer part of the square root of the input.
lcm(*integers)
Least Common Multiple.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
nextafter(x, y, /)
Return the next floating-point value after x towards y.
perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order.
Evaluates to n! / (n - k)! when k <= n and evaluates
to zero when k > n.
If k is not specified or is None, then k defaults to n
and the function returns n!.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
pow(x, y, /)
Return x**y (x to the power of y).
prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method.
ulp(x, /)
Return the value of the least significant bit of the float x.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
(built-in)
In [14]:
a = -12.99
print(floor(fabs(a)))
12
In [15]:
a = -12.99
print(fabs(floor(a)))
13.0
In [16]:
import math
l = [str(round(math.pi)) for i in range(1, 6)]
print(l)
['3', '3', '3', '3', '3']
In [17]:
round(3.4)
Out[17]:
3
In [20]:
round(3.5)
Out[20]:
4
In [19]:
round(3.6)
Out[19]:
4
In [1]:
# Modules :-
# random
# selenium
# faker
# math
# os
# re
In [ ]:
In [1]:
# Functions :-
# A group of repeatedly required lines
# Code Reusability
# Modules :-
# Python File
# A group of functions, varibales, classes saved to a file
# # Packages :-¶
In [3]:
# Basic Java Package
# core java + advanced java + oracle
# Complete Python Package
# Core Python + Advanced Python + UI + Django + Django Rest Framework + Microsoft Certification
# Complete Body Checkup Package
# Hear Checkup Package
# South India Tour Package
# 10 places
In [4]:
# A collection of python lines into a single unit ---> Function
# A collection of python functions, variable and classes into a single file ---> Module
# A collection of related modules into a folder ---> Package
In [7]:
# A collection of related modules into a single unit is nothing but package.
# Package is an encapsulation mechansim to group related modules into a single unit.
# Package is simply a folder or directory.
# If folder contains __init__.py file is considered as python package.
# A python package can contains sub package also but all packages should contain __init__.py file.
# From Python 3.3 version onwards, it is not mandatory to have __init__.py file.
In [8]:
# Advantages of Packages :-
# 1. We can resolve naming conflicts.
# 2. We can identify our components uniquely.
# 3. It imporoves modularity of the application.
# 4. It improves readability and maintainability of the applications.
In [ ]:
In [4]:
# C:\Python
# |-test.py
# |-com
# |-__init__.py
# |-module1.py (contains f1 function)
# |-durgasoft
# |-__init__.py
# |-module2.py (contains f2 function)
In [5]:
# from com.module1 import f1
# f1()
In [6]:
# from com.durgasoft.module2 import f2
# f2()
# Importance of init.py File :-¶
In [15]:
# At the time of using a package, if we want to perform any initialization activites automatically then we have to go for __init__.py
In [12]:
# but if we write print statement in noraml module also it will be executed?
# but we have to call the function in which print statement while in __init__.py it will be executed automatically.
In [14]:
# If we have __init__.py file in folder and subfolder then.
# when we call folder then only folder __init__.py will execute
# ex. from com.module import f1
# in this only folder __init__.py file will execute automatically
# when we call sub-folder then folder and sub-folder __init__.py will execute
# ex. from com.durgasoft.module2 import f1
# in this folder and sub-folder __init__.py file will execute automatically
# Need of Installing a Package :-¶
In [18]:
# If we wnat to use a package, compulsory it should be available in the current working directory.
# To make package available through out our system then we have to install that package. Once we installed we can access that package from anywhere in our system.
In [19]:
# exec('function_name')
In [ ]:
# How to Install Package :-¶
In [2]:
# from setuptools import setup
# setup(name="patterns", version="1.0", packages=["patterns"])
In [3]:
# pip is a python package management system to install and manage software packages written in python.
In [5]:
# pip install .
In [7]:
# # Alternative Way :-
# from setuptools import setup, find_packages
# setup(name="patterns", version="1.0", packages=find_packages())
In [8]:
# pip uninstall patterns
In [10]:
# pip install django (installing django library)
# pip install pymysql
# pip install selenium (for automation)
In [11]:
# pip ---> python package management software system
# npm ---> javascript
# apt ---> Ubuntu
# yum ---> redhat linux
# # Library vs Package vs Module vs Function :-¶
In [14]:
# Function ---> A group of repeatedly required lines of code.
# Module ---> A group of repeatedly required functions, variables, classes saved to a file.
# Package ---> A group of related modules into a single folder. It contains sub packages.
# Library ---> A group of packages.
In [ ]:
# # File Handling :-¶
In [2]:
# We required to store data
# student marks
# customers account information
# billing information
In [5]:
# Files are very common permanent storage areas to store our data.
# list, tuple, set, dict ===> available as long as program is in running. Once program completes these objects will be destroyed automatically and hence the data will be gone. Temporary storage areas.
In [4]:
d = {}
for i in range(3):
name = input("Enter Name :")
balance = int(input("Enter Balance :"))
d[name] = balance
print(d)
{'asdbj': 45, 'dsafda': 2452, 'asdfas4': 24}
In [6]:
# Permanent Storage Areas :-
# files
# database
# big data technologies/cloud
# Types of Files :-¶
In [9]:
# 2 Types of Files :-
# 1. text files :
# abc.txt, test.py
# 2. Binary Files:
# images, video files, audio files etc
# Opening of a File :-¶
In [13]:
# f = open(filename, mode)
# Example :-
f = open("abc.txt", "r")
data = f.read()
print(data)
This is Python Practice
In [15]:
# # The allowed modes are:
# r, w, a, r+, w+, a+, x
# 1. r :-¶
In [27]:
# Open an existing file for read operation. The file pointer is at begining of the file.
# FileNotFoundError
# default mode is red mode
# 2. w :-¶
In [29]:
# Open an existing file for write operation.
# Overwrite of existing data will be happened.
# If the specified file not already availabel, then this mode will create that file.
In [20]:
f = open('abc.txt', 'w')
# 3. a :-¶
In [31]:
# Open an existing file for append operation.
# It won't overwrite of existing data will be happened.
# If the specified file not already availabel, then this mode will create that file.
# 4. r+ :-¶
In [32]:
# To read and write data.
# The previous data won't be overwritten.
# 5. w+ :-¶
In [35]:
# To write and read data.
# It will overwrite existing data.
# 6. a+ :-¶
In [37]:
# It append and read.
# It won't overwrite existing data.
# 7. x :-¶
In [39]:
# To open a file in exclusive createion mode.
# Specified file should not be avaialable already, otherwise we will get FileExistsError
# # 2. Binary File :-¶
In [41]:
# rb
# wb
# ab
# r+b
# w+b
# a+b
# xb
# Closing of a File :-¶
In [43]:
f.close()
# Various Properties of File Object :-¶
In [46]:
f = open("abc.txt", "r")
In [47]:
# f.name ---> Name of opened File
# f.module ---> Mode in which we opened that file.
# f.closed ---> Is the file closed (True/False)
# f.readable() ---> Returns True if the file is readable
# f.wrtable() ---> Returns True if the file is writable
In [51]:
f = open("abc.txt", "r")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : r Is File Readable : True Is File Writable : False Is File Closed : False Is File Closed : True
In [1]:
f = open("abc.txt", "w")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : w Is File Readable : False Is File Writable : True Is File Closed : False Is File Closed : True
In [2]:
f = open("abc.txt", "r+")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : r+ Is File Readable : True Is File Writable : True Is File Closed : False Is File Closed : True
In [3]:
f = open("abc.txt", "w+")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : w+ Is File Readable : True Is File Writable : True Is File Closed : False Is File Closed : True
In [4]:
f = open("abc.txt", "a")
print("File Name :", f.name)
print("File Mode :", f.mode)
print("Is File Readable :", f.readable())
print("Is File Writable :", f.writable())
print("Is File Closed :", f.closed)
f.close()
print("Is File Closed :", f.closed)
File Name : abc.txt File Mode : a Is File Readable : False Is File Writable : True Is File Closed : False Is File Closed : True
In [ ]:
# Write Data to the text Files :-¶
In [2]:
# 2 METHODS :-
# f.write(str)
# f.writelines(list of lines)
In [6]:
f = open("abc.txt", "w")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [14]:
f = open("abc.txt", "w+")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [13]:
f = open("abc.txt", "r+")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [12]:
# Data will be written in existing file without resenting file
f = open("abc.txt", "a+")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [15]:
# Data will be written in existing file without resenting file
f = open("abc.txt", "a")
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [18]:
f = open("abc.txt", "x")
f.write("Durga ")
f.write("Software ")
f.write("Solutions ")
print("Data Written to the File Successfully")
f.close()
--------------------------------------------------------------------------- FileExistsError Traceback (most recent call last) Cell In[18], line 1 ----> 1 f = open("abc.txt", "x") 3 f.write("Durga ") 4 f.write("Software ") File c:\Users\pulki\anaconda3\envs\Personal\Lib\site-packages\IPython\core\interactiveshell.py:324, in _modified_open(file, *args, **kwargs) 317 if file in {0, 1, 2}: 318 raise ValueError( 319 f"IPython won't let you open fd={file} by default " 320 "as it is likely to crash IPython. If you know what you are doing, " 321 "you can use builtins' open." 322 ) --> 324 return io_open(file, *args, **kwargs) FileExistsError: [Errno 17] File exists: 'abc.txt'
In [19]:
# f.writelines(list of lines) :-
In [20]:
f = open("abc.txt", "w")
l = ["Bunny", "Chinny", "Sunny", "Pinny", "Vinny"]
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [21]:
f = open("abc.txt", "w")
l = ["Bunny\n", "Chinny\n", "Sunny\n", "Pinny\n", "Vinny\n"]
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [22]:
# write(str)
# multiple strings ---> multiple write() methods
# writelines(list|ste|tuple|dict)
In [24]:
f = open("abc.txt", "w")
l = ("Bunny\n", "Chinny\n", "Sunny\n", "Pinny\n", "Vinny")
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [26]:
f = open("abc.txt", "w")
l = {"Bunny\n", "Chinny\n", "Sunny\n", "Pinny\n", "Vinny"}
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
# for set order wise no guaranttee
Data Written to the File Successfully
In [27]:
f = open("abc.txt", "w")
l = {"A": 100, "B": 200, "C": 300}
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [28]:
f = open("abc.txt", "w")
l = {100: "A", 200: "B", 300: "C"}
f.writelines(l)
print("Data Written to the File Successfully")
f.close()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[28], line 4 1 f = open("abc.txt", "w") 2 l = {100: "A", 200: "B", 300: "C"} ----> 4 f.writelines(l) 6 print("Data Written to the File Successfully") 7 f.close() TypeError: write() argument must be str, not int
In [30]:
f = open("C:\\GNA\\abc.txt", "w")
f.write("First Line\n")
f.write("Second Line\n")
f.write("Third Line\n")
print("Data Written to the File Successfully")
f.close()
Data Written to the File Successfully
In [33]:
fname = input("Enter File Name:")
f = open("C:\\GNA\\" + fname + ".txt", "w")
while True:
data = input("Enter Data to Write:")
f.write(data + "\n")
option = input("Do you want to add some more data[Yes|No]:")
if option.lower() == "no":
break
print("Your Provided Data Written to the File Successfully")
f = open("C:\\GNA\\" + fname + ".txt", "r")
print(f.read())
f.close()
Your Provided Data Written to the File Successfully durga software solutions
# Reading Data from Files :-¶
In [35]:
# read() ---> To read total data from the file
# read(n) ---> To read n characters from the file
# readline() ---> To read only one line
# readlines() ---> To read all lines into a list
In [36]:
f = open("abc.txt", "r")
data = f.read()
print(data)
Sunny Bunny Chinny Vinny Pinny Munny
In [39]:
f = open("abc.txt", "r")
data = f.read(10)
print(data)
Sunny Bunn
In [40]:
f = open("abc.txt", "r")
data = f.readline()
print(data)
Sunny
In [47]:
f = open("abc.txt", "r")
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
data = f.readline()
print(data)
Sunny Bunny Chinny Vinny Pinny Munny
In [48]:
data = f.readline()
print(data)
data = f.readline()
print(data)
In [51]:
# After lines are finished while using f.readline() then it will keep on reading/printing empty lines.
# f.readline() will automatically add new empty line after each new line.
In [46]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
['Sunny\n', 'Bunny\n', 'Chinny\n', 'Vinny\n', 'Pinny\n', 'Munny']
In [ ]:
In [11]:
f = open("abc.txt", "r")
line = f.readline()
while line != "":
print(line)
line = f.readline()
f.close()
Sunny Bunny Chinny Vinny Pinny Munny
In [12]:
f = open("abc.txt", "r")
line = f.readline()
while line != "":
print(line, end="")
line = f.readline()
f.close()
Sunny Bunny Chinny Vinny Pinny Munny
In [13]:
f = open("abc.txt", "r")
line = f.readline()
while line != "":
if line != "\n":
print(line, end="")
line = f.readline()
f.close()
Sunny Bunny Chinny Vinny Pinny Munny
In [14]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
['Sunny\n', 'Bunny\n', 'Chinny\n', '\n', 'Vinny\n', 'Pinny\n', 'Munny']
In [17]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
for line in data:
print(line)
['Sunny\n', 'Bunny\n', 'Chinny\n', '\n', 'Vinny\n', 'Pinny\n', 'Munny'] Sunny Bunny Chinny Vinny Pinny Munny
In [18]:
f = open("abc.txt", "r")
data = f.readlines()
print(data)
for line in data:
print(line, end="")
['Sunny\n', 'Bunny\n', 'Chinny\n', '\n', 'Vinny\n', 'Pinny\n', 'Munny'] Sunny Bunny Chinny Vinny Pinny Munny
In [23]:
f = open("abc.txt", "r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print(f.read())
Sun ny Bunn y Chinny Vinny Pinny Munny
In [28]:
# Read data from input.txt and write to output.txt?
In [29]:
f1 = open("input.txt", "r")
f2 = open("output.txt", "w")
data = f1.read()
f2.write(data)
f1.close()
f2.close()
print("Data Copied Successfully")
Data Copied Successfully
# with statement :-¶
In [31]:
with open("abc.txt", "w") as f:
f.write("DURGA\n")
f.write("SOFTWARE\n")
f.write("SOLUTIONS\n")
print("Is File Closed:", f.closed)
print("Is File Closed:", f.closed)
Is File Closed: False Is File Closed: True
In [33]:
# When we use with statement file will be closed automatically we are not required to close the file.
# The file will close automatically when we are out of with statement.
In [38]:
f1 = open("abc.txt", "w")
f2 = open("abc.txt", "a")
f2.write("hello")
f1.write("Hi")
f2.close()
f1.close()
with open("abc.txt", "r") as f:
print(f.read())
Hihellohello
In [40]:
# # Advantages of with statement :-
# 1. To group file operation in a block
# 2. To close the file automatically
In [ ]: